9

When using the mouse wheel to scroll down a page, the mouseleave event is not firing in IE11 until the cursor is moved. Works fine in Google Chrome.

jsFiddle: http://jsfiddle.net/tonyleeper/5vwf65f7/

HTML

<div class="box">Move the mouse cursor inside this box and observe the mouseenter event fires (background goes green). Next, use the mouse wheel to scroll down without moving the mouse cursor position, observe the mouseleave event doesn't fire. Finally, move the mouse cursor even a little, say 1px, and observe that the mouseleave event then fires</div>

CSS

.box {
    font-family: arial;
    font-size: 16px;
    width: 300px;
    height: 200px;
    background-color: #000077;
    color: #ffffff;
}

JavaScript

var box = document.getElementsByClassName('box')[0];

box.addEventListener('mouseenter', function (e) {
    document.body.setAttribute('style', 'background-color: #007700');
});

box.addEventListener('mouseleave', function (e) {
    document.body.setAttribute('style', 'background-color: #ffffff');
});

Are there any known workarounds for this to force the event to fire on scroll?

jQuery would appear to have the same issue: https://api.jquery.com/mouseleave/

magritte
  • 7,396
  • 10
  • 59
  • 79
  • The apparent difference is the IE doesn't update the mouse position after scrolling, whereas chrome does. Triggering mousemove doesn't seem to work to force it to update... – Tony Hinkle Oct 09 '15 at 15:20
  • 3
    I'm using chrome version 45.0.2454.101 and it's the same behavior as IE11 - does not update when scrolling away and not moving the mouse. This might just be the expected behavior. – Shahar Oct 12 '15 at 10:03
  • @Shahar That's odd, I'm also on Chrome 45.0.2454.101 and I can see the behaviour is different from IE, scrolling away fires mouseleave – magritte Oct 12 '15 at 11:48
  • It is odd, although now it behaves like you describe. I think it's related to the window's focus (sometimes when the window is out of focus the behavior is strange). – Shahar Oct 12 '15 at 12:03

1 Answers1

2

You could put your listener into a function and also attach a scroll eventListener. There you could check if the mouse cursor is still 'inside' the 'box' and call the appropriate function:

var triggerOnMouseLeave = function(e) {
    document.body.setAttribute('style', 'background-color: #ffffff');
}

box.addEventListener('mouseleave', triggerOnMouseLeave);

var triggerOnScroll = function(e) {
    // Using jQuery here
    if (!$(box).is(':hover')) {
        triggerOnMouseLeave();
    }
}

window.addEventListener('scroll', triggerOnScroll);
Dr1Ku
  • 2,875
  • 3
  • 47
  • 56
Luuuud
  • 4,206
  • 2
  • 25
  • 34