Sergi
Sergi

Reputation: 1240

What's the correct syntax to select individual elements?

In this instance when I hover over any of the columns all of the .p1 elements in the page fade in. How can I have only the element I'm currently hovering over to fade in and not the rest?

$('.column1, .column2, .column3, .column4, .column5').mouseenter(function() {
    $(".p1").fadeIn(200);
    $(this).animate({
        height: '100%'
    });
});


$('.column1, .column2, .column3, .column4, .column5').mouseleave(function() {
    $(".p1").fadeOut(200);
    $(this).animate({
        height: '100px',
    }); 
}); 

Upvotes: 0

Views: 16

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337550

Use the this keyword to reference the element that triggered the event, like this:

$('.column1, .column2, .column3, .column4, .column5').mouseenter(function() {
   $(this).fadeIn(200).animate({
       height: '100%'
    });
});

$('.column1, .column2, .column3, .column4, .column5').mouseleave(function() {
    $(this).fadeOut(200).animate({
        height: '100px'
    }); 
}); 

Also note that you can shorten the code by using a common class on all the elements, using the hover() handler and fadeToggle(). Try this:

$('.column').hover(function() {
    $(this).fadeToggle(200).animate({
        height: $(this).height() == 100 ? '100%' : '100px'
    }); 
}); 

Upvotes: 2

Related Questions