Why won't drag event trigger on first attempt?

31 Views Asked by At

I have a javascript application in which I'm trying to handle a drag event but it requires two attempts to drag:

enter image description here

I want the user to be able to drag the handle on the track position bar so that they can skip ahead or go back anywhere in the track. But for some reason, the user has to attempt it twice. The first time they attempt to drag, the handle doesn't move (and the drag handler doesn't fire). On the second attempt it does.

Here is the code:

<div class="track-position-container">
    <div class="position-bar">
        <div class="completed-bar"></div>
        <div class="position-nob" ondrag="positionNobDragged(event)" ondragend="positionNobDragEnded(event)"></div>
    </div>
</div>
function positionNobDragged(event) {
    const positionBar = document.querySelector('.position-bar');
    const positionNob = document.querySelector('.position-nob');
    const completedBar = document.querySelector('.completed-bar');

    const x = event.x - positionBar.offsetLeft;

    positionNob.style.left = x;
    completedBar.style.width = completedBar.style.left + x;
}

function positionNobDragEnded(event) {
    positionNobDragged(event);
}

You can go here to try it: http://planetshah.com/mixes/mix.html?mix=65

Does anyone know why the drag handler won't respond on the first attempt to drag the handle?

1

There are 1 best solutions below

1
On

Looking at function positionNobDragged(event), there's a few bugs.

This is causing negative values when you only drag a little...

const x = event.x - positionBar.offsetLeft;

Just set your left directly...

const x = event.x;

positionNob.style.left = x + positionBar.offsetLeft;

I think it's reluctant to move at the first drag because of negative values generated.