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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With