I want to activate a context-menu only after left-mousedown is pressed for N seconds (e.g. 2 seconds).
If the mouse is released, the context-menu should not be shown.
I tried to use:
But I cannot get the expected behaviour.
What I get is a delay before showing the context-menu for the first time, but:
How can I condition showing the context-menu, only after the mouse is clicked for a specified time period?
Thanks
You can reach it with this solution
const MouseDownDuration = class {
setMouseDown() {
this.downAt = new Date();
}
setMouseUp() {
this.upAt = new Date();
}
get duration () {
return this.upAt.getTime() - this.downAt.getTime()
}
}
const contextMenu = new MouseDownDuration();
document.querySelector('#element').addEventListener('mousedown', (e) => {
contextMenu.setMouseDown();
});
document.querySelector('#element').addEventListener('mouseup', (e) => {
contextMenu.setMouseUp();
// Log the diff in milliseconds
console.log(contextMenu.duration);
// Eventually dispatch a custom event
});
You can also see how to dispatch an event using e.target element by checking https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events