Tyharo Tyharo - 5 months ago 11
jQuery Question

Sort onclick only working once

I have a script that will sort a list of divs based on their data attribute. The sort functions are tied to clickable divs based on ID. Currently when I click one of the divs the items will sort correctly but only once. After sorting by ascending order(up) I'am unable to sort by descending(down) unless I refresh the page.
jsfiddle: https://jsfiddle.net/4ttjxwme/2/
Below is the script, any help is appreciated!

<script>
$(document).ready(function () {
$("#down").on('click', function(){
var sortedDivsDown = $(".unsorted").find("div").toArray().sort(sorterDown);
$.each(sortedDivsDown, function (index, value) {
$(".loanIndicators ").append(value);
});
function sorterDown(b, a) {
return b.getAttribute('rel') - a.getAttribute('rel');
};
});
});

$(document).ready(function () {
$("#up").on('click', function(){
var sortedDivsUp = $(".unsorted").find("div").toArray().sort(sorterUp);
$.each(sortedDivsUp, function (index, value) {
$(".loanIndicators ").append(value);
});
function sorterUp(a, b) {
return a.getAttribute('rel') - b.getAttribute('rel');
};
});
});
</script>

Answer

Since you are using jquery object references for the sortedArrays var sortedDivsDown = $(".unsorted").find("div").toArray().sort(sortDown);, the second time around, the .unsorted div element is empty and the elements are now in the .loanIndicators div.

You can fix this by using the below selector to find the indicator div elements:

var sortedDivsDown = $(".unsorted,.loanIndicators").find("div").toArray().sort(sortDown);

var sortedDivsUp = $(".unsorted,.loanIndicators").find("div").toArray().sort(sortUp);

This will work in your case, since all the elements will be in either of the two div elements.

Here is a working JSFiddle

Comments