I have div called “panel” that itself contains another div. When a user clicks (and holds the mouse down) on “panel” and drags left or right, the inner div is dragged left or right. When the user releases the click, the dragging of the inner div is stopped. For the most part, this works without issue.
The problem that I’m encountering is when a user is dragging and the mouse leaves “panel”, the dragging continues. In such a situations, when the user releases the mouse button, the dragging still continues as the mouseup event is not being reached presumably because the mouseup event is occuring outside of “panel”.
Here’s the code that I’m using:
$(document).ready(function() {
$('#panel').bind("mousedown", function (e) {
StartDrag(); // Code to drag inner panel goes here
}).bind("mouseup", function (e) {
StopDrag(); // Code to stop drag goes here
}).bind("mouseout", function (e) {
$(this).unbind("mousedown"); // This line doesn't help
StopDrag();
});
});
If I bind the StopDrag() function to the entire document then it interferes with StartDrag().
How can I ensure that I can trigger my StopDrag() function upon mouseup regardless of where it occurs?
First, you should broaden your event handlers to respond to the whole document, not just the panel, so that if the mouse moves quickly enough to escape and the events go to the document, you’ll still handle them.
However, there is still a problem if the mouse leaves the window entirely. I wrestled with this problem myself, and determined that this is a longstanding problem with the DOM API that has no solution. If the mouse leaves the window while the button is down, you cannot detect when the button is released. When the mouse reenters the window, there is no way to find out whether the mouse button is still down.