Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select parent & all children elements while using mouseover, jQuery

I have a div with elements (h3, img, p) inside. I want to use jQuery to detect when a user hovers over this div to then toggle a class of an element in this div.

I'm using the code below:

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

This works as expected when hovering over just the div. If you hover over an element inside the div (eg. .entry h2) it toggles the class off as though it has left the parent div (.entry) but it's actually inside it. The elements are not floating inside div.entry which I had thought might throw it off. I tried $(".entry *") and $(".entry, .entry *") but both of these have similar issues.

Any thoughts?

like image 643
mrhigham Avatar asked Nov 08 '11 00:11

mrhigham


1 Answers

Try using mouseenter and mouseleave instead.

Here's the relevant piece of documentation about mouseenter vs mouseover:

The mouseenter event differs from mouseover in the way it handles event bubbling. If mouseover were used in this example, then when the mouse pointer moved over the Inner element, the handler would be triggered. This is usually undesirable behavior. The mouseenter event, on the other hand, only triggers its handler when the mouse enters the element it is bound to, not a descendant.

Here's an example that might help; note what events are fired off when you move your pointer in and out of elements.

like image 90
Andrew Whitaker Avatar answered Oct 27 '22 21:10

Andrew Whitaker