Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/jQuery: Reordering divs according to data-attribute values [duplicate]

Possible Duplicate:
Sort element by numerical value of data attribute

I want to reorganize divs according to a data attribute set on them, ranging from highest integer to lowest. Right now, I push all the data into an array and sort that but I'm not sure how to proceed. How can I use this to reorganize divs inside their parent div?

var prices = new Array();
$(this).children('.listing-item').each(function() {
    var price = parseInt($(this).attr('data-listing-price'));
    prices.push(price)
});
prices.sort(function(a,b){return b-a});

This gets me an array like 139,129,129,109,109,84 for example. Now my idea was to loop through the divs another time with a selector like this:

$('.listing-item[data-listing-price="' + prices[0] + '"]')

but I'm not sure how to move the divs (the div with the highest data-attribute integer should move to the top and so on. Any idea?

like image 368
Galadre Avatar asked Jan 21 '13 12:01

Galadre


1 Answers

Here is the solution

HTML:

<div id="list">
  <div class="listing-item" data-listing-price="2">2</div>
  <div class="listing-item" data-listing-price="3">3</div>
  <div class="listing-item" data-listing-price="1">1</div>
  <div class="listing-item" data-listing-price="4">4</div>
</div>

JS:

var divList = $(".listing-item");
divList.sort(function(a, b){
    return $(a).data("listing-price")-$(b).data("listing-price")
});
$("#list").html(divList);

JSFiddle:

http://jsfiddle.net/bittu4u4ever/ezYJh/1/

like image 79
Sandeep Avatar answered Oct 06 '22 11:10

Sandeep