4

I have an element with some child elements. When the mouse leaves the parent element I want to hide the parent and it's children. Problem I'm having is that when I hover over any of the children, the mouseout event is being fired. What's the best way to prevent this? I really only want the event to fire when the mouse is not within the parent or any of it's children.

Matt
  • 6,264
  • 10
  • 54
  • 82
  • 2
    I think you mean you're having a problem with `mouseover`/`mouseout`. `mouseenter` and `mouseleave` are specifically designed to *not* function the way you describe. – Crescent Fresh Feb 08 '10 at 04:09
  • Yup, my bad. I mean mouseover / mouseout – Matt Feb 08 '10 at 04:11
  • This very similar to this question [Onmouseover child div problem and event bubbling](http://stackoverflow.com/questions/2206828/onmouseover-child-div-problem-and-event-bubbling) which I [answered](http://stackoverflow.com/questions/2206828/onmouseover-child-div-problem-and-event-bubbling/2206875#2206875) – meouw Feb 08 '10 at 09:43

3 Answers3

3

The event is bubbling up from the child to the parent (where it is being caught)

You should catch the event on the children by adding a listener and making the propagation stop there.

This code will stop the event from bubbling up to the parents handler

function onMouseLeave(e)
{
    if (!e) var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
}

question: The mouse off event is fired by the parent, when it should not. Mouseing over the child should not trigger a mouse off from the parent. How can we stop this?

Steven
  • 166,672
  • 24
  • 332
  • 435
linead
  • 1,636
  • 14
  • 25
3

You only need a mouseout handler attached to the parent element. But...

You need to check that the parent is actually the target of the mouseout event, as opposed to the event bubbling up from one of the children. Check event.target (W3C) and event.srcElement (IE).

You also need to check that the element that the mouse will be entering is not a descendant of the parent. Check event.relatedTarget (W3C) and event.toElement (IE).

Sean Hogan
  • 2,902
  • 24
  • 22
2

From http://api.jquery.com/mouseover/:

mouseover fires when the pointer moves into the child element as well, while mouseenter fires only when the pointer moves into the bound element.

and the same goes for mouseout vs mouseleave

Anton
  • 2,282
  • 26
  • 43