0

I need to track mouseenter / mouseleave events for all elements on the page.

Intuitively written code for it was:

$(window).on('mouseenter mouseleave', function(e) {
  console.log(e.target, e.type);
  // ...
});

But it fires mouseleave events every time mouseenter happens on child element, thus nullifying all benefits of mouseenter/mouseleave, i.e. it works like mouseover/mouseout.

Is there a way to handle this without attaching handlers directly to all elements?

And does this look like a jQuery bug? Because from what I know and from jQuery docs I've read it looks like the above code should work fine.

JSBin to play with: http://jsbin.com/axuluc/2/

Edit: this works as expected: http://jsbin.com/axuluc/9/

Georgii Ivankin
  • 2,702
  • 2
  • 23
  • 35
  • Do you mean you need to track for literally all elements? For example, every `
    `, ``, etc.?
    – adamdehaven Mar 14 '13 at 12:16
  • It works just fine, but when the mouse enters a new element, it leaves another element, like you would expect! – adeneo Mar 14 '13 at 12:16
  • You want to track mouseenter/leave for all elements, but it fires for every child element... Isn't that what you want? Can you describe what you are trying to achieve? the jsbin seems to work as expected for me, in Chrome anyway. – Andrew Grothe Mar 14 '13 at 12:16
  • I don't want "mouseleave" to be triggered when I move from an elements to its child. This is the whole thing about "mouseenter/mouseleave" events. – Georgii Ivankin Mar 14 '13 at 12:19
  • Then just remove the `mouseleave` part ? – adeneo Mar 14 '13 at 12:20
  • @adeneo I want to track mouseleave. But I want it to behave like mouseleave, i.e. I don't want it triggered when I move from element to its children. I only want it to be triggered when I really move mouse outside the element. – Georgii Ivankin Mar 14 '13 at 12:26
  • It works as I want it to work if I replace "window" with "*", but it cancels the benefit of delegation. – Georgii Ivankin Mar 14 '13 at 12:29

2 Answers2

1

Well child elements are included in all definition, aren't they?

Give the desired elements a class if possible like class="mouse_active" or use proper selector.

Then...

$(window).on('mouseenter mouseleave','.mouse_active', function(e) {
  console.log(e.target, e.type);
  // ...
});

and you still attach a single handler

kidwon
  • 4,448
  • 5
  • 28
  • 45
0

This is the right way to do it:

$(window).hover(
   function(){
      // mouse enter function...
   },
   function(){
      // mouse leave function...
   }
);

http://api.jquery.com/hover/

BorisD
  • 2,231
  • 5
  • 25
  • 35
  • This is **not** the right way to do it, it's exactly the same as the OP's code, as hover() is just a jQuery shortcut for mouseenter and mouseleave ? – adeneo Mar 14 '13 at 13:10