Is there a way to have both of these work together or do I have to try using the mouseenter and mouseleave instead?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With