Select parent and all children elements when using mouseover, jQuery

I have a div with elements (h3, img, p) inside. I want to use jQuery to detect when the user is hovering over this div, then to switch the element class in this div.

I am using the following code:

$('.entry').bind({ mouseover: function() { $('.readMore').toggleClass('inverted'); }, mouseleave: function() { $('.readMore').toggleClass('inverted'); } }); 

This works as expected when hovering over a div only. If you hover over an element inside a div (e.g. .entry h2 ), it will disable the class as if it left the parent div ( .entry ), but it is actually inside it. Elements do not float inside div.entry which I thought could throw it away. I tried $(".entry *") and $(".entry, .entry *") , but both have similar problems.

Any thoughts?

+4
source share
1 answer

Try using mouseenter and mouseleave .

Here is the relevant part of the documentation about mouseenter vs mouseover :

The mouseenter event differs from mouseover in the way it handles the event bubble. If mice were used in this example, then when the mouse pointer moves over the internal element, the handler will fire. This is usually an undesirable behavior. The mouseenter event, on the other hand, only fires its handler when the mouse enters the element to which it is bound, and not the child.

Here is an example that might help; notice what events fire when you move the pointer in and out of elements.

+13
source

Source: https://habr.com/ru/post/1380104/


All Articles