Last active
June 19, 2017 21:54
-
-
Save marcelitocs/876edd2c70e47f16e595b4dd5f0b6c2d to your computer and use it in GitHub Desktop.
Plugin jQuery para ordenar elementos do DOM a partir de um callback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Copyright 2017 Marcelito Costa | |
https://gist.github.com/marcelitocs/876edd2c70e47f16e595b4dd5f0b6c2d | |
Exemple of use | |
$(".table tbody tr").sortElements(function(a, b){ | |
if(a.data("vencimento") < b.data("vencimento")){ | |
return -1; | |
} | |
if(a.data("vencimento") > b.data("vencimento")){ | |
return 1; | |
} | |
return 0; | |
}); | |
*/ | |
(function ($) { | |
if(typeof $.fn.sortElements === "undefined") { | |
$.fn.sortElements = function (compareFunction) { | |
var $elements = this; | |
var $firstTr = $elements.first(); | |
var $lastTr = $elements.last(); | |
var internalSort = function () { | |
$elements.each(function () { | |
var $this = $(this); | |
if (compareFunction($this, $firstTr) < 0) { | |
$this.detach().insertBefore($firstTr); | |
$firstTr = $this; | |
internalSort(); | |
return false; | |
} | |
if (compareFunction($this, $lastTr) > 0) { | |
$this.detach().insertAfter($lastTr); | |
$lastTr = $this; | |
internalSort(); | |
return false; | |
} | |
var $prev = $this.prev(); | |
if (compareFunction($this, $prev) < 0) { | |
$this.detach().insertBefore($prev); | |
internalSort(); | |
return false; | |
} | |
var $next = $this.next(); | |
if (compareFunction($this, $next) > 0) { | |
$this.detach().insertAfter($next); | |
internalSort(); | |
return false; | |
} | |
}); | |
}; | |
internalSort(); | |
return this; | |
}; | |
} | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment