Sort the div in alphabetical order using data attribute


JavaScript • JQuery


"<script type=\"text/javascript\" src=\"//code.jquery.com/jquery-1.11.0.js\"></script>"

Data sample

<div id="contentblock">
     <div>Resort by: <a href="javascript:resortByTitle();">Name</a>, <a href="javascript:resortByCategory();">Category</a></div>
     <div id="viewcontent">
          <div class="rgridwrapper" data-title="Beer Mustard" data-export-category="Spreads">
          <div class="rgridwrapper" data-title="Billy Bi Soup - Cream of Mussels with Saffron" data-export-category="Soups">
     </div>
</div>


function resortByTitle() {
	var alphabeticallyOrderedDivs = $('.rgridwrapper').sort(function(a, b) {
		return String.prototype.localeCompare.call($(a).data('title').toLowerCase(), $(b).data('title').toLowerCase());
	});	
	var container = $("#viewcontent");
	container.detach().empty().append(alphabeticallyOrderedDivs);
	$('#contentblock').append(container);	
}

function resortByExportCategory() {
	var alphabeticallyOrderedDivs = $('.rgridwrapper').sort(function(a, b) {
		return String.prototype.localeCompare.call($(a).data('export-category').toLowerCase(), $(b).data('export-category').toLowerCase());
	});	
	var container = $("#viewcontent");
	container.detach().empty().append(alphabeticallyOrderedDivs);
	$('#contentblock').append(container);	
}

Written by Dedrick, Brian Tompsett, and Axelduch from http://stackoverflow.com/questions/27836169/sort-the-div-in-alphabetical-order-using-data-attribute

Posted by fbrefere001 on Monday September 5, 2016