Martijn Ebbens
Martijn Ebbens

Reputation: 253

Sorting a div based on data attribute in jQuery

Alright, I'm trying to make it so jQuery sorts the divs when a button is clicked,

Let's say the list looks like this,

<div class="wrapper">
  <div class="item" data-worth="720">Edgy</div>
  <div class="item" data-worth="420">Blaze</div>
  <div class="item" data-worth="666">Meme</div>
</div>

Then after the button is clicked I want it to spit out,

   <div class="wrapper">
      <div class="item" data-worth="720">Edgy</div>
      <div class="item" data-worth="666">Meme</div>
      <div class="item" data-worth="420">Blaze</div>
    </div>

Basically sorting worth from low to high, rearanging everything and putting it back in the wrapper.

I'm honestly clueless on how I'd go on doing this, I thought of using jQuery's .each function but then I'd only be able to get highest value on the top, any suggestions?

Upvotes: 6

Views: 6501

Answers (3)

rollingthedice
rollingthedice

Reputation: 1125

HTML:

<div class="wrapper">
  <div class="item" data-worth="720">Edgy</div>
  <div class="item" data-worth="420">Blaze</div>
  <div class="item" data-worth="666">Meme</div>
</div>
<button class="clickMe">Sort</button>

JavaScript:

function someFunction(){
  var $wrapper = $('.wrapper');
    $wrapper.find('.item').sort(function (a, b) {
    return +b.dataset.worth - a.dataset.worth;
})
.appendTo( $wrapper );
}
$('body').on('click', '.clickMe', someFunction);

Here is a working: JSFiddle

Upvotes: 0

JGV
JGV

Reputation: 5187

//code taken from: https://stackoverflow.com/questions/6133723/sort-divs-in-jquery-based-on-attribute-data-sort

//All I have done is, presented the code such a way that it is easy for you to understand and use it in your application

function asc_sort(a, b){ return ($(b).data("worth")) > ($(a).data("worth")) ? 1 : -1; }

jQuery.fn.sortDivs = function sortDivs() {
    $(".item", this[0]).sort(asc_sort).appendTo(this[0]);
}

$('#BtnSort').on('click', function(){
    $(".wrapper").sortDivs();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="BtnSort">Sort</button>
<div class="wrapper">
  <div class="item" data-worth="720">Edgy</div>
  <div class="item" data-worth="420">Blaze</div>
  <div class="item" data-worth="666">Meme</div>
</div>

Upvotes: 0

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

Sort the wrapper's divs based on their data('worth'), then append the sorted list back to the wrapper:

$('button').click(function() {
  $('.wrapper div').sort(function(a, b) {
    return $(b).data('worth') - $(a).data('worth');
  }).appendTo('.wrapper');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Sort</button>
<div class="wrapper">
  <div class="item" data-worth="720">Edgy</div>
  <div class="item" data-worth="420">Blaze</div>
  <div class="item" data-worth="666">Meme</div>
</div>

Upvotes: 9

Related Questions