Jon
Jon

Reputation: 49

How do I prevent jQuery .hover function from affecting all images simultaneously?

I'm not sure the title explains it well enough, but was trying to keep it quite short!

So, I've got a number of images scattered around a page and have created a lightbox gallery for them all (.cboxElement is the class that calls it). What i wanted to add into this was a hover effect on each image affected by the lightbox so the user knows it can be zoomed.

The problem:

I didn't write the original code for the site and this is a new feature. Due to inconsistencies in classes across images, I had to prepend a tag before each image with a unique class for the hover method to refer to, as follows:

    $("a.cboxElement").each(function(){
        $(this).prepend("<span class='zoom'></span>");
    });

Immediately following this, I've used the hover effect:

    $("a.cboxElement").hover(function(){
        $("a.cboxElement span").fadeIn('fast');
    },
    function(){
        $("a.cboxElement span").fadeOut('fast');
    });

The problem is that when I hover over an image on the page, the hover effect appears on every image simultaneously and I can't work out how to get it to affect only the image I'm hovering over.

Does anyone have any ideas as to what I could do?

Many thanks,

Jon

Upvotes: 1

Views: 724

Answers (4)

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107508

I think you just need to change the scope of your hover assignment:

$("a.cboxElement").hover(function(){
    $(this).find("span").fadeIn('fast');
},
function(){
    $(this).find("span").fadeOut('fast');
});

Your original code was saying: for each a.cboxElement, find all a.cboxElement elements' spans and fade them in/out. The above code says for each a.cboxElement, on hover, find the span for just this a.cboxElement and fade it in/out.

Upvotes: 3

karim79
karim79

Reputation: 342635

Also, you can use .fadeToggle with a single function:

$("a.cboxElement").hover(function(){
    $(this).find("span").fadeToggle("fast");
});

Upvotes: 1

El Yobo
El Yobo

Reputation: 14946

$("a.cboxElement").hover(function(){
    $(this).find('span:first').fadeIn('fast');
},
function(){
    $(this).find('span:first').fadeOut('fast');
});

Upvotes: 0

Blazemonger
Blazemonger

Reputation: 92893

Assign an id="..." attribute to each image and select it instead of the entire a.cboxElement class:

<img id="imageid1" ... >
$('#imageid1')....

Upvotes: 0

Related Questions