I'm trying to move an element by watching mousemove events on the document while the element is being dragged (using html5 drag and drop). I added a mousemove listener on the document on a parent element that fires whenever I move my mouse, but once I start dragging another child element I stop seeing mousemove events and once I stop dragging I see the events again. I don't see it anywhere in the API (https://developer.mozilla.org/en-US/docs/Web/Events/mousemove) that dragging disables these events, but I can't tell how I could be stopping them from my code. Is this just part of html5 drag and drop that it disables the mousemove events while dragging?
I am using angular2 to detect mousemove. I've tried two different ways:
1)
@HostListener('document:mousemove', ['$event'])
onMouseMove(event) {
console.log('Global mousemove: ', event);
}
2)
constructor(
public element: ElementRef,
private renderer: Renderer2) {
element.nativeElement.draggable = true;
}
this.mouseMoveListener = this.renderer.listen('document', 'mousemove', this.onMouseMove.bind(this));
From here: "The mousemove event is fired when a pointing device (usually a mouse) is moved while over an element." When you're dragging the element mouse is not moving over it - instead it moves synchronously with the element. I think you should consider "ondrag" event for this purpose - see here.
You can use a pointermove
event, that does the job ;)
You're right, mousemove
events are disabled while an element is being dragged. You need to listen to a drag
event instead (or perhaps to both mousemove
and drag
, depending on what you need). The drag event works even with a global handler.
document.addEventListener('drag', (e) => console.log(e.clientX, e.clientY))
You can test this with a dummy draggable element:
<div draggable>Test</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With