Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properly keeping track of which (nested) div has mouse-over

I have a (deeply) nested structure of <div>s. With Javascript, I'd like to keep track of which element the mouse is currently over (i.e., 'has focus'), where more deeply nested elements have priority:

Desired mouse-over behavior in nested divs

I've tried combinations of mouseover, mouseout, mouseenter, mouseleave and mousemove, but there seems to be no simple solution that gives me the expected behavior. I am able to receive mouse-events on the right divs, but often these events are subsequently received by higher level divs, which would then undeservedly take focus.

For example, in the transition above from a to c, the event might then be received by b last, unintentionally giving focus to b rather than c. Or the transition from c to b might not be registered at all for some reason.

I don't understand the underlying mechanism of mouse-event propagation well enough to come up with a reliable solution. It seems like it should be such a simple thing, but I can't figure it out.

I've been able to get it to work as follows: when a div receives a mouseenter/over event, flag it and search the entire DOM subtree. If any other flags are found deeper down, relinquish focus. But this is rather crude, and I can't help but think there must be an easier way.

Edit: Solution

The use of mouseover and mouseout, combined with a call to stopPropagation() seems to work very well. Here is a JSFiddle to show the working solution.

like image 410
mhelvens Avatar asked May 08 '14 12:05

mhelvens


People also ask

When the mouse moves over a link then which event is called?

The mouseover event occurs when a mouse pointer comes over an element, and mouseout – when it leaves.

What is the difference between Mouseenter and mouseover?

The mouseover event triggers when the mouse pointer enters the div element, and its child elements. The mouseenter event is only triggered when the mouse pointer enters the div element.

Which event is triggered when mouse enters a specific region?

The mouseenter event is fired at an Element when a pointing device (usually a mouse) is initially moved so that its hotspot is within the element at which the event was fired.

Which menu appears as the user moves the mouse cursor over a parent menu item?

Typically the hidden menu, or submenu, is shown on a hover event, when a user moves the mouse over a parent item.


1 Answers

You can use the event stopPropagation() method:

https://developer.mozilla.org/en-US/docs/Web/API/event.stopPropagation

If using jQuery, try calling stopPropagation() on the event passed as the first parameter

http://api.jquery.com/event.stoppropagation/

$( "p" ).on('mouseover', function( event ) {
  event.stopPropagation();
  // Do something
});

Also, you can check which element is the target, as in event.target.

like image 92
Meligy Avatar answered Sep 20 '22 10:09

Meligy