Get and keep only original target of mousedown event?

Viewed 134

I want to get and keep only the original target element of a mousedown event -- but as the user holds the mouse down, the event.target changes depending on what's under the pointer.

There is a property event.originalTarget which does exactly what I want, but it's only supported by Firefox (reference: https://developer.mozilla.org/en-US/docs/Web/API/Event/originalTarget ).

How can I replicate this behavior using standard event.target?

1 Answers

Figured it out: you need to create flags outside the event listener.

let el = false
let mousedown = false;

document.addEventListener('mousedown', ev => {
        if (!mousedown) {
            el = ev.target;
            mousedown = true;
        }
    });

document.addEventListener('mouseup', ev => {
        mousedown = false;
        el = false;
    });

So el will be set as the original target for the duration of the mousedown, but on mouseup, it's reset back to nothing.

Related