KThornbloom
KThornbloom

Reputation: 11

How to have multiple instances of a jQuery effect

First, the disclaimer- I'm JUST starting out with jQuery. I apologize for my ineptness. :)

My issue is that I'm attempting to use a jQuery rollover effect on a bunch of separate elements on a page. Right now, when I mouse over one, they all do the effect at once because they have the same class name, and jQuery is selecting all of them. I know I could use a different name for each, and write a separate bit of jQuery for each class, but is there a better way? I plan on having many of these elements.

Anyway, a picture is worth a thousand words. Check out the source of my test page here: Click Here Mouse over the 'test' images. I want the effect to just apply to the one you mouse over.

Here's my novice jQuery:

    $(document).ready(function(){

$('.box').hover(function() {
 $('.rollover').fadeIn('slow');
 $('.description').fadeIn('fast');
});

$('.box').mouseleave(function() {
 $('.rollover').fadeOut('slow');
 $('.description').fadeOut('fast');
});


});

Upvotes: 1

Views: 241

Answers (2)

KThornbloom
KThornbloom

Reputation: 1

If I could select them one at a time, I think I could apply the effect only to their children. I just wish you could tell jquery to just select whatever your mouse is over without stating an ID or Class...

Upvotes: 0

user113716
user113716

Reputation: 322562

$('.box').hover(function() {
   $(this).next('.rollover').fadeIn('slow');
   $(this).find('.description').fadeIn('fast');
}, function() {
   $(this).next('.rollover').fadeOut('slow');
   $(this).find('.description').fadeOut('fast');
});

The .hover() method accepts two functions to fire for mouseenter and mouseleave.

Within each function, the this keyword refers to the .box element that received the event. Then you use .find() to get the nested .description, and .next() to get the adjacent sibling .rollover.

In your situation, you could use .siblings('.rollover') instead of .next() if you want.

Upvotes: 3

Related Questions