Reputation: 1237
Right now I'm stopping drag events on mouse up, like so:
$(document).mouseup(_onMouseUp);
However I need to capture mouse up events when the mouse leaves the browser window, similar to releaseOutside
in Flash.
Is this possible in JS?
Upvotes: 14
Views: 13906
Reputation: 3919
It is possible to capture mouse up event outside of browser window like below:
elem.addEventListener('mousedown', function(e) {
...
elem.setPointerCapture(e.pointerId);
});
elem.addEventListener('mouseup', function(e) {
...
elem.releasePointerCapture(e.pointerId);
});
References: setPointerCapture releasePointerCapture
Upvotes: 6
Reputation: 3218
You can capture mouseup events outside the browser window in every major browser: Chrome, Edge and Firefox.
You just need to attach the listener to the 'window' object, like this:
window.addEventListener('mouseup',
() => console.log('mouse up captured outside the window'));
https://codepen.io/fredrikborgstrom/pen/vRBaZw
or in your case, using jQuery, it would be:
$(window).mouseup(_onMouseUp);
Upvotes: 10
Reputation: 462
Yes, it is possible to capture mouseup events outside the browser window. Just call Element.setCapture() inside mousedown callback.
Remember to call document.releaseCapture() on mouseup also.
elem.addEventListener('mousedown', function() {
...
elem.setCapture();
});
elem.addEventListener('mouseup', function() {
...
document.releaseCapture();
});
Upvotes: 10
Reputation: 11210
You can't detect a mouseup or mousedown event outside of the browser window, but I think what you are trying to do is cancel a drag or drop when the user clicks off the browser window. You can accomplish that, by reacting to the browser window losing focus, e.g.:
$(window).on("blur", function(e) {
// Cancel my drag and drop here
});
or
$(document).on("blur", function(e) {
// Cancel my drag and drop here
});
This covers you for mouse clicks outside the browser window, and also things like Windows Alt+Tab task switching.
Upvotes: 9