Reputation: 22243
i have this page:
<div class="products">
<div id="product-1" class="product">
<a href="#" title="View this" class="product-a">
<img class="product-img" src="/product.png" alt="Image of this product" /><span class="stilt"></span>
<div class="product-info">
<h3 class="product-title"><span>This Product</span></h3>
<p class="product-price"><span>Product price</span></p>
</div>
</a>
</div>
<div id="product-2" class="product">
<a href="#" title="View this" class="product-a">
<img class="product-img" src="/product.png" alt="Image of this product" /><span class="stilt"></span>
<div class="product-info">
<h3 class="product-title"><span>This Product</span></h3>
<p class="product-price"><span>Product price</span></p>
</div>
</a>
</div>
...
</div>
i was wondering if there is a way to sort the product-# divs by their .product-info.product-title ascending or descending with javascript, how can i do that?
Upvotes: 2
Views: 1095
Reputation: 111
I-d use jQuery to catch all product elements and underscore javascript to sort.
Products:
<div class="products">
<div class="product">
<div class="name">B name</div>
</div>
<div class="product">
<div class="name">C name</div>
</div>
<div class="product">
<div class="name">A name</div>
</div>
</div>
<br/>
Sort Products:
<button id="asc">Ascending</button>
<button id="desc">Descending</button>
<script type="text/javascript">
function sortList(dir) {
var $products = $('.products .product');
var sorted = _.sortBy($products, function(product){
return $(product).find('.name').html();
});
if (dir == "desc") {
sorted.reverse();
}
$('.products').append($(sorted));
}
$('#asc').click(function() {
sortList('asc');
});
$('#desc').click(function() {
sortList('desc');
});
</script>
Although jQuery and underscore rock together, if you need to load both libraries only for this sorting and nothing else, it would be couple of kb-s of excess code loaded.
Upvotes: 4