Why does mouse up trigger drag event?

29 Views Asked by At

I have a javascript application in which I'm trying to handle a drag event but the drag event listener seems to listen for the mouse up event (dragend) as well as the drag event, and this is causing issues. The application is a playlist player. It loads a playlist and allows the user to listen to it with controls as shown below:

enter image description here

The drag event happens on the handle for the track position bar. The user can click and drag the handle to move forward or back in the track that's currently playing.

I set it up like this:

...
<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;

    console.log(`x = ${x}`);
    console.log(`event.x = ${event.x}`);
    console.log(`left = ${positionBar.offsetLeft}`);

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

function positionNobDragEnded(event) {
    console.log('drag ended');
}

Note the console logs. When I drag the handle (the nob) and then lift my mouse when I'm at where I want to be, it outputs this:

...
x = 103
event.x = 141
left = 38
x = 104
event.x = 142
left = 38
x = 105
event.x = 143
left = 38
x = -38
event.x = 0
left = 38
drag ended

You'll note a couple things: 1) the last set of outputs shows event.x = 0. This is when I lift the mouse button (i.e. it's registering as a drag event). 2) the drag end event fires after the last drag event triggered by mouse up (I therefore can't use it to flag that the drag has ended in positionNobDragged() on the last drag event (where event.x = 0)).

This is causing the handle to end up on the left edge of the screen (far off the track position bar) even though I can drag it to where I want it to be. As soon as I lift my mouse, it ends up on the left edge of the screen (because event.x = 0):

enter image description here

So my question is: why does lifting the mouse count as a drag event instead of JUST a dragend event? And is there any way for me to detect in positionNobDragged() that it was triggered by a mouse up (and ignore it in that case)? I'd look for event.x = 0 but that could be an actual position the user dragged the mouse to.

Thanks for any forthcoming help.

0

There are 0 best solutions below