Costa Costa - 5 months ago 10
CSS Question

Applying transform with JavaScript on mousemove doesn't update on the fly

trying to make a div draggable, but only along the x-axis, the way a timestamp thumb on a video control can be dragged left and right to seek through a video or audio presentation.

Here's my code

thumb.addEventListener('mousemove', updateThumbPosition, false)

function updateThumbPosition (event) {
var thumbRect = thumb.getBoundingClientRect()
var startX = seekbar.getBoundingClientRect().left
var mouseX = event.clientX
console.log(mouseX - startX + thumbRect.width / 2)
thumb.style.transform = 'translateX(' + mouseX - startX + thumbRect.width / 2 + 'px)'
}


The div doesn't move. The values change rapidly as the mouse moves. I can see that when I log to the console, but the div itself does not translate along the X axis. Thoughts?

Here's a jsfiddle: https://jsfiddle.net/btjLqa8u/1/

Answer

You're only missing parentheses: https://jsfiddle.net/rjzLtunb/

 div.style.transform = 'translateX(' + (mouseX - startX) + 'px)'

By the way, for drag and drop code, you probably want to listen for mouse moves on the div parent instead of the div itself.

Comments