Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

e.stopPropagation() and jQuery.hover()

Is there a way to have both of these work together or do I have to try using the mouseenter and mouseleave instead?

like image 911
Copper Avatar asked Nov 30 '22 05:11

Copper


1 Answers

You can use event.stopPropagation() with .hover(), but you're actually using mouseenter and mouseleave with .hover() anyway. If you provide 1 function to .hover(), it runs on both events, if you provide 2 functions, the first is the mouseenter handler, the second is the mouseleave handler.

However, this may not be what you're after...since mouseenter doesn't fire when entering a child, that's actually specifically why it exists, mouseout will fire when entering a child. You can see that's there's no difference in a demo here, hover from top to bottom, comment and uncomment out the .stopPropagation(), it makes no difference...because the event doesn't bubble to the parent.

However if you are using mouseover and mouseout, then it would matter, like this:

$("li").mouseover(function(e) {
    $(this).addClass("red").parents().removeClass("red");
}).mouseout(function(e) {
    $(this).removeClass("red");
});​

Now we have a bubbling problem, because the event bubbles right up, adding the class to the parent we just removed it from, see a demo of the problem here. However if we stop that bubble, with the .stopPropagation(), we get the desired effect, like this:

$("li").mouseover(function(e) {
    $(this).addClass("red").parents().removeClass("red");
    e.stopPropagation();
}).mouseout(function(e) {
    $(this).removeClass("red");
});​

You can see in this demo how this works differently.

In short: yes event.stopPropagation() works with .hover(), but most likely, it's not exactly what you're after.

like image 130
Nick Craver Avatar answered Dec 14 '22 00:12

Nick Craver