32

I have a set of list elements (<li> within a <ul>) laid out as bubbles on a chart like this, where the bubbles are the <li> elements:

https://i.stack.imgur.com/PR7vR.png

I want to be able to detect the difference between

  1. Moving the mouse from bubble #1 to the grid
  2. Moving the mouse from bubble #1 directly to another bubble, such as bubble 2

I've attempted to use $(this) in the .mouseleave() even for a bubble, but it registers the element that you're leaving rather than the element that you're currently hovering.

Any ideas on how to get the element that the mouse is moving onto upon mouseleave()?

Tyler Nieman
  • 375
  • 1
  • 4
  • 9

2 Answers2

57

You need to use event.toElement || e.relatedTarget:

$('li').mouseleave(function(e)
{
    // new element is: e.toElement || e.relatedTarget
});

(Edited to note || e.relatedTarget to ensure browser compatibility)

N Rohler
  • 4,595
  • 24
  • 20
  • 1
    Note edit I added above based on good call by @kennebec - to ensure that you have browser compatibility, it's a good idea to reference `e.toElement || e.relatedTarget` instead of just `e.toElement` – N Rohler Oct 13 '11 at 23:28
  • 1
    e.relatedTarget is the official solution: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/relatedTarget – Taurus Nov 10 '22 at 13:46
8

If you can use ordinarey javascript, every event (e) mouse over and mouse out has an e.relatedTarget in most browsers. IE before #9 has event.toElement and event.fromElement, depending on if you are listening to a mouseover or mouseout.

somebody.onmouseout=function(e){
  if(!e && window.event)e=event;
  var goingto=e.relatedTarget|| event.toElement;
  //do something
}
somebody.onmouseover=function(e){
  if(!e && window.event)e=event;
  var comingfrom=e.relatedTarget|| e.fromElement;
  //do something
}
kennebec
  • 102,654
  • 32
  • 106
  • 127