vabm vabm - 3 months ago 17
HTML Question

Sort DIVs by attribute with JQuery

I am trying to use buttons to sort a number of

DIV
using custom attributes. I was following this example but cannot make it work with custom attributes. I know there might be a problem with the way I am accessing the attributes, but not sure how to fix it.

My
HTML
is:

<button id="opBnt">OP</button>
<button id="inBnt">IN</button>
<div id="collapsible" class="panel-collapse">
<div id="1" class="superduper" data-sort-op="0.4" data-sort-in="0.1">a</div>
<div id="2" class="superduper" data-sort-op="0.2" data-sort-in="0.8">b</div>
<div id="3" class="superduper" data-sort-op="0.3" data-sort-in="0.3">c</div>
</div>


And
JS
:

var $divs = $("div.superduper");
$('#opBnt').on('click', function () {
var opOrder = $divs.sort(function (a, b) {
return $(a).getAttribute('data-sort-op') > $(b).getAttribute('data-sort-op');
});
$("#collapsible").html(opOrder);
});

$('#inBnt').on('click', function () {
var inOrder = $divs.sort(function (a, b) {
return $(a).getAttribute('data-sort-in') > $(b).getAttributel('data-sort-in');
});
$("#collapsible").html(inOrder);
});


Fiddle

Answer
  1. The sort function should return -1, 0, 1 values.
  2. You can use the data function to access data-* attributes.

Check this example:

var $divs = $("div.superduper");
$('#opBnt').on('click', function () {
    var opOrder = $divs.sort(function (a, b) {
        return $(a).data('sort-op') < $(b).data('sort-op') ? -1 : 1;
    });
    $("#collapsible").html(opOrder);
});

$('#inBnt').on('click', function () {   
    var inOrder = $divs.sort(function (a, b) {
        return $(a).data('sort-in') < $(b).data('sort-in') ? -1 : 1;
    });
    $("#collapsible").html(inOrder);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="opBnt">OP</button>      
<button id="inBnt">IN</button>
<div id="collapsible" class="panel-collapse">                   
    <div id="1" class="superduper" data-sort-op="4" data-sort-in="1">a</div>
    <div id="2" class="superduper" data-sort-op="2" data-sort-in="8">b</div>
    <div id="3" class="superduper" data-sort-op="3" data-sort-in="3">c</div>
</div>