I'm building a photo gallery and what I would like to do is make it so that as the user rolls over an image (let's say for the purposes of this question it's a picture of an apple), all the other images of apples on the page also show their "over" state.
Any and all help would be greatly appreciated, and thank you for your time in advance!
You could add the 'type' of the image as a class. For example an apple will be:
<img src='' class='apple fruit red' />
You can have as many space separated classes as you want.
Then add the following handler:
$(".apple").mouseover(function() {
$(".apple").addClass("overState");
});
You need to define in your CSS the overState. On mouseout you must remove the class.
So each image has a number of tags (eg: "apple", "red", "big"), and when you mouse over the big red apple, you want all other apples, big things and red things to light up?
As kgiannakakis suggested, I'd put that data into the class attribute of the image - the only difference is that I'd prefix each class with something so you don't clash with other classes on your page.
<img src="the-big-red-apple.jpg" class="tagged tag-big tag-red tag-apple" />
I've also added an extra class there called "tagged" so you can tell your tagged photos from navigational images or whatever.
$('img.tagged')
.each(function() {
var thisClasses = this.className.split(/s+/); // array of classes.
var search = [];
for (var i = 0; i < thisClasses.length; ++i) {
if (thisClasses[i].substr(0, 4) == "tag-") {
search.push("." + thisClasses[i]);
}
}
$(this).data("tags", search.join(",")); // ".tag-big,.tag-red,.tag-apple"
})
.hover(function() {
$('img.tagged')
.filter(this.data('tags'))
.addClass("highlight")
;
}, function() {
$('img.tagged')
.filter(this.data('tags'))
.removeClass("highlight")
;
})
;
What this does is initially loop through all your tagged images and work out what the tags are on each of them, storing that into that element's data(). This means we only need to do that once, and not each time.
Then it adds a hover event to each tagged image to find anything which matches any of this image's tags and add the "highlight" class. Similarly it removes the class when you mouseout.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With