Catching mouse event outside of browser / window

Right now I am stopping mouse drag events like:

$(document).mouseup(_onMouseUp);

However, I need to capture mouse events when the mouse leaves the browser window, similar to releaseOutside

in Flash.

Is this possible in JS?

+3


source to share


3 answers


You cannot detect a mouseup or mousedown event outside of the browser window, but I think you are trying to do this to undo the drag when the user clicks the browser window. You can accomplish this by reacting to the browser window by losing focus, for example:

$(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, as well as things like Windows Alt + Tab task switching.

+8


source


Yes, it is possible to capture mouse events outside of the browser window. Just call Element.setCapture () inside the mousedown callback.

Don't forget to call document.releaseCapture () on mouseup.



elem.addEventListener('mousedown', function() {
    ...
    elem.setCapture();
});
elem.addEventListener('mouseup', function() {
    ...
    document.releaseCapture();
});

      

+4


source


You can capture mouseup events outside the browser window in every major browser: Chrome, Edge, and Firefox.

You just need to attach a listener to the 'window' object , for example:

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);

      

0


source







All Articles