I am trying to drag an image with Javascript (no libraries). I am able to listen to mousedown
and mousemove
events. For some reason, I am not able
Strangely, I've found that when I set my text as unselectable using the below CSS, that inhibits the mouseup
event from firing as well -- perhaps this will help someone else.
-moz-user-select: none;
-khtml-user-select: none;
user-select: none;
Found the issue, if it is going to be of help to anyone:
I added event.preventDefault();
in the mousedown
event and now I am getting mouseup
notifications.
I was running into this exact same issue! Adding event.preventDefault();
worked for me but I was forced to add it to both the mousedown and mousemove functions.
I have seen the mouseup
event not fire on my target div
because its parent div
began consuming drag events. I clicked my target div
and this caused my mousedown
and mousemove
handlers to run. I was expecting to see a mouseup
but I did not.
In my case, I had a parent div
living beneath my target div
in the same location where I launched my mouse button click, and instead of bubbling up the mouseup
event on my document once I let go of the left mouse button, I instead got a dragend
event fire on its parent div
.
The solution for me was simply to set user-select: none;
CSS property on the parent div
which houses my target div
and to make sure I set user-select: text
on my target div
. This property seems to disable dragging for my parent div
and because it has stopped consuming drag events, my mouseup
event now properly bubbles its way up.
I presume the reason why this might happen is because the browser starts thinking your mouse move is actually part of a drag event on another element, at which point it seems to stop reporting the standard mouse events and switches to drag events instead.
Neither of the above answers reliably worked to ensure a mouseup event.
Here's what I discovered works consistently:
document.querySelector('html').addEventListener('mouseup', function (e) {
console.log("html mouseup");
var evt = document.createEvent("MouseEvents");
evt.initEvent("mouseup", true, true);
document.getElementById('drag-me').dispatchEvent(evt);
});
If mouseup fires on target element, it does not fire on html, and if it did not fire on target, it will fire on html.