Open
Description
What problem are you trying to solve?
const button = document.querySelector('button');
button.addEventListener('click', (event) => {
// …
});
I want to add activation behavior to the above button, such as "when this button is clicked, toggle this checkbox". As expected on the platform, I don't want this action to happen if a listener calls event.preventDefault()
.
What solutions exist today?
const button = document.querySelector('button');
button.addEventListener('click', (event) => {
if (event.defaultPrevented) return;
checkCustomCheckbox();
});
This isn't great because the default may be prevented by a listener further along the path.
const button = document.querySelector('button');
button.addEventListener('click', (event) => {
setTimeout(() => {
if (event.defaultPrevented) return;
checkCustomCheckbox();
}, 0);
});
This isn't great because the effect may happen a frame later (rAF
isn't a reliable solution here due to whatwg/html#10113). It's also observably async:
button.click();
console.log(customCheckboxChecked); // expected true, but got false
Other techniques, like adding listeners to window
may be missed due to stopPropagation()
, and may still be 'beaten' by another listener.
How would you solve it?
Something like:
const button = document.querySelector('button');
button.addEventListener('click', (event) => {
event.addActivationBehavior(() => {
checkCustomCheckbox();
});
});
Anything else?
No response
Activity