vendredi 28 novembre 2014

Sorting HTML divs in front-end using JS/jQuery


Consider the following HTML block representing a review of a product (content omitted for brevity):



<div class="reviews">
<div class="review-item" id="someUniqueIdPerReviewItem">
<div class="review-header">
<div class="review-user">
</div>
<div class="review-date">
</div>
</div>
<div class="review-info">
<div class="review-rating">
</div>
<div class="review-message">
</div>
</div>
</div>
</div>


Each product will have as many "review-item" divs in it's "review" div as it has reviews.


I'm returning this HTML in a View using Razor in MVC. I sort the reviews chronologically in the Action of the view's Controller prior to passing the reviews to my view.


Let's say that I want give the user the facility to order the reviews by other metrics, e.g. date ASC/DESC, rating ASC/DESC and so on. What is the most reliable way to do this in the frontend? Obviously, I would like to avoid making AJAX calls to the controller and passing a "sorting parameter" to rerender pretty much the exact same content in different order.


I'm already using jQuery to do some frontend calculations, animations etc but I'm a beginner in frontend development. I would guess that I could use jQuery to do something like this?



1. loop through every "review-item" in "reviews" and store it in a collection
2. sort the collection based on a particular property of "review-item"
3. clear the "reviews" div and append the collection to it


If not, what would be an appropriate way to achieve this?


Thanks!





Aucun commentaire:

Enregistrer un commentaire