javascript - Sorting HTML divs -
i have database table list of images. each image has data attached, name , value. using table, create html code php make grid on screen, each image/name/value table.
this php generates html:
//makes div each item in table echo "<li id=div" . $i . ">"; //content single grid block echo '<center><h3 id="credits' . $i . '">' . $credit_value . " credits" . '</h3></center>'; echo "<img id='item" . $i ."' src= '$new_link' title='$row[item_name]' class='clickableimage' alt='$just_name' data-creditvalue='" . $credit_value . "' data-imagenumber='" . $i . "'border=0 style='position: center; top: 0; left: 0;'/>"; echo '<center><h3 id="quality">' . $quality . '</h3></center>'; echo '</li>';
this makes each div named "div1", "div2" etc. in //content
section, printed image data-imagename=$imagename
, data-imagevalue=$value
, though should able attach divs holding content well.
what want add buttons @ top of page sort image grid categories. loaded in order of items in database table, example, have button clicked after grid loaded, changes orders of divs, in alphabetical order, or lowest->highest valule.
how can this?
edit: here example of html generated above code.
<li id="div2"> <center> <h3 id="credits2">108 credits</h3> </center> <div style="position: relative; left: 0; top: 0;"> <img id="item2" src="http://steamcommunity-a.akamaihd.net/economy/image/fwfc82js0fmorap-qoipu5thswqfsmtellqcuywgkijvjzymursm1j-9xgeobwgfeh_nvjlwhnzzcvecdfibj98xqodq2czknz56p7fidz9-tqxjvfdsxfgf9gt5dbg-4cbrqjnv8emdkgnutigtzeepyt8dh5ltu_epnwj-ue9s1azveptb9czu33zpjc5udl2z8fjg/155fx118f" title="ak-47 | blue laminate (minimal wear)" class="clickableimage" alt="ak-47 | blue laminate " data-creditvalue="108" data-imagenumber="2" border="0" style="position: center; top: 0; left: 0;"> <img src="images/tick.png" id="tick2" class="hidden" style="position: absolute; top: 0px; left: 70%;"> </div> <center> <h3 id="quality">minimal wear</h3> </center> </li>
it's pretty easy sort nodes jquery (and in pure js too). need use sort
methods delegates array.prototype.sort
, provide custom comparator functions.
in case want able sort string title number, create 2 separate functions , use them depending on button clicked:
<button onclick="sort('title', 'string')">sort name</button> <button onclick="sort('data-creditvalue', 'number')">sort value</button>
and sort
function be
var comparators = { string: function(a, b) { return a.localecompare(b); }, number: function(a, b) { return number(a) - number(b); } }; function sort(attr, type) { var $container = $('ul'), $li = $container.find('li'); $li.sort(function(a, b) { var aval = $(a).find('img').attr(attr), bval = $(b).find('img').attr(attr); console.log(aval) return comparators[type](aval, bval); }).appendto($container); }
Comments
Post a Comment