Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 691
Martijn Ebbens Avatar asked Aug 28 '17 21:08

Martijn Ebbens


1 Answers

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>
like image 161
Rick Hitchcock Avatar answered Nov 03 '22 13:11

Rick Hitchcock