user3898993
user3898993

Reputation: 21

Hover function for nested elements

I've got <div class="lewy"> and many other divs inside. When I hover div "lewy" my jQuery function works, but when I move pointer to any nested div it doesn't. How can I make it to work?

I want to implement this behaviour to all inner divs.

$(".lewy").hover(function() { 
    $(".lewy").animate({width: 600}, 100);
});

$(".lewy").mouseout(function() { 
    $(".lewy").animate({width: 300}, 50);
});

Upvotes: 1

Views: 403

Answers (1)

Guffa
Guffa

Reputation: 700152

The mouseenter event and mouseleave event are constructed for exactly this scenario.

$(".lewy").mouseenter(function() { 
  $(".lewy").animate({width: 600}, 100);
});
$(".lewy").mouseleave(function() { 
  $(".lewy").animate({width: 300}, 50);
});

Side notes: You can chain the methods as they are applied to the same elements. You would want to use $(this) in the handler instead of $('.lewy') if it applies to more than one element (and otherwise just because it's faster, simpler and more maintainable). You normally want to stop any potential previous animation before starting one to prevent that they queue up:

$(".lewy").mouseenter(function() { 
  $(this).stop().animate({width: 600}, 100);
}).mouseleave(function() { 
  $(this).stop().animate({width: 300}, 50);
});

Upvotes: 4

Related Questions