Reputation: 57
We have 100+ images on page. Each image has 3 parameters:
How do I sort images on page with this parameters (i want to see blue+panorams+2007) without page reloading - just selecting the right images?
P.S. I don't know how to sign parameters, in class i guses like class="2009 yellow blue portrait" without using external files
Upvotes: 0
Views: 609
Reputation: 11149
I'm going to assume the following markup... you can adapt it to your own:
<div id="images">
<div>
<img src="..." />
<em>Year: </em><span class="year">2007</span>
<em>Color: </em><span class="color">red</span>
<em>Type: </em><span class="type">portrait</span>
</div>
<div>
<img src="..." />
<em>Year: </em><span class="year">2008</span>
<em>Color: </em><span class="color">yellow</span>
<em>Type: </em><span class="type">panoram</span>
</div>
</div>
Then this is the jQuery you'll need:
function sortBy(field) {
var container = $('#images');
// get a real array of the image divs
var imgDivList = container.children().get();
// Put them into the correct order based on the chosen field
imgDivList.sort(function (a, b) {
var aText = $(a).children('.' + field).text();
var bText = $(b).children('.' + field).text();
if (aText < bText) {
return 1;
}
if (aText > bText) {
return -1;
}
if (aText == bText) {
return 0;
}
});
// Append them back to the original container
container.append(imgDivList);
}
For filtering, do this:
function filter(field, value) {
var imgDivList = $('#images').children();
imgDivList.each(function (index, element) {
if ($(element).children('.' + field).text() == value) {
$(element).show();
} else {
$(element).hide();
}
});
}
Upvotes: 3
Reputation: 92943
This is the general idea. You need to create a true array of the images, then sort them using JavaScript array.sort
and a custom function. Once that's done, you can append
them right back to the DOM and they'll rearrange themselves.
arrImages = $('img').get(); // need a true array
arrImages.sort(function(a,b) {
// write your own sort function here using your parameters
// return a negative number to sort a before b, positive to sort b before a
});
$.each(arrImages, function(i,el) {
$('#container').append(el);
});
Upvotes: 0