I have a tag element for a web page. when clicking once, one logic is executed, when clicking twice, another. However, the DOM only responds to one click and fires immediately, no matter how quickly you try to fire a double click event.
How do I use these two events on one element?
export const createTag = (name) => {
const tag = document.createElement('span');
tag.innerHTML = name;
tag.addEventListener('dblclick', () => {
tags.removeChild(tag);
storeTags.splice(storeTags.indexOf(name), 1);
});
tag.addEventListener('click', () => {
search.value = tag.innerHTML;
const keyboardEvent = new KeyboardEvent('keypress', {
code: 'Enter',
key: 'Enter',
charCode: 13,
keyCode: 13,
view: window,
bubbles: true,
});
storeTags.splice(storeTags.indexOf(name), 1);
storeTags.unshift(name);
search.dispatchEvent(keyboardEvent);
});
return tag;
};
The basic idea to achieve this would be to add some small delay to the click operation, and cancel that if a dblclick is received. This does lead to reduced responsiveness of your UI, as your application is now having to explicitly distinguish between single and double clicks in a kind of "wait and see" approach. This can also be unreliable as the user may set any length of time as their double-click threshold in their device's Accessibility settings.
However, if these issues are deemed not to be enough of a concern, the "best of the worst" way to do this would be to manually implement double-click checks.
export const createTag = (name) => {
const tag = document.createElement('span');
tag.innerHTML = name;
const clickHander = () => {
search.value = tag.innerHTML;
const keyboardEvent = new KeyboardEvent('keypress', {
code: 'Enter',
key: 'Enter',
charCode: 13,
keyCode: 13,
view: window,
bubbles: true,
});
storeTags.splice(storeTags.indexOf(name), 1);
storeTags.unshift(name);
search.dispatchEvent(keyboardEvent);
};
const dblClickHandler = () => {
tags.removeChild(tag);
storeTags.splice(storeTags.indexOf(name), 1);
};
let clickTimer;
tag.addEventListener('click', () => {
if( clickTimer) {
clearTimeout(clickTimer);
dblClickHandler();
clickTimer = null;
}
else {
clickTimer = setTimeout(() => {
clickHandler();
clickTimer = null;
}, 500);
}
});
return tag;
};
Adjust the timer as you feel appropriate. Smaller numbers will lead to more responsive clicks, but will make double-clicking harder for people with reduced mobility.
I would really strongly recommend using a different UI here. Overloading clicks in this way is a really bad idea in general.