How does mouse movementX work on drag events?
Asked Answered
C

2

7

I am trying to set up dynamic draggable element which will move its anchor point according to the drag delta. However I cannot seem to get the delta using event.movementX or event.movementY.

My simple drag event code:

mainMenuDiv.addEventListener("drag", (event)=>{
   console.log(event.movementX, event.movementY);
});

// The console print out is simply:
//>0 0
// This prints out a lot of times as i drag the mouse but doesn't change the properties.

I think i am missing something about the way the movement property works with drag events.

Calhoun answered 15/2, 2018 at 12:3 Comment(0)
M
4

I couldn't get it to work either, so I just did the following:

var start = null, delta = null

el.addEventListener('dragstart', e => {
    start = {x: e.clientX, y: e.clientY}
})

el.addEventListener('drag', e => {
    delta = {x: e.clientX - start.x, y: e.clientY - start.y}
})

el.addEventListener('dragend', e => start = delta = null)
Motheaten answered 26/9, 2018 at 23:29 Comment(0)
K
-1

You can use e.nativeEvent.offsetX and e.nativeEvent.offsetY, too.

I don't know the browser support though.

Kaleidoscopic answered 30/10, 2021 at 10:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.