Last Updated: February 25, 2016
·
14.56K
· pornel

JS mouse events that work even when mouse is moved outside the window

It's not guaranteed that mousedown will be followed by mouseup on any element in the document!

If you ever expect mousedown to happen on any DOM node, you're creating a "sticky mouse button" bug.

document.body.onmouseup = // NO, this is a bug!

Instead you should only listen to mouseup on window:

window.onmouseup = function(e) {…}

or better:

window.addEventListener('mouseup', function(e) {…}, false);

The same applies to mousemove event. It will fire even when mouse pointer leaves the window and your scripts tracking the mouse won't go blind and glitchy when mouse pointer moves outside document's viewport.

You can see it in action in Slip.js.

3 Responses
Add your response

nice

over 1 year ago ·

This does not work when the mouse pointer leaves the window (in Chrome). Any suggestions?.. I'm trying to implement this, any help woul be much appriciated :)

over 1 year ago ·

@finalelement I've verified it works in Chrome. See dragging example at http://pornel.net/slip/ - obviously the drag must start when mouse is in the window, but then when it leaves the window the script can still see the position and mouseup event.

over 1 year ago ·