JavaScript Event.defaultPrevented
Whether you started with the old on_____
property or addEventListener
, you know that events drive user experiences in modern JavaScript. If you've worked with events, you know that preventDefault()
and stopPropagation()
are frequently used to handle events. One thing you probably didn't know: there's a defaultPrevented
proptery on events!
Consider the following block of code:
// Specific to a link const link = document.querySelector('#my-link'); link.addEventListener('click', e => e.preventDefault()); // A larger document scope document.addEventListener('click', documentClickHandler); function documentClickHandler(event) { if (event.defaultPrevented) {// Using the property // Do one thing if the click has been handled } else { // Otherwise do something fresh } }
When preventDefault
is called on a given event, the defaultPrevented
property gets toggled to true
. Due to event propagation, the event bubbles upward with this defaultPrevented
value.
I've been handling events for two decades and didn't know this property existed until now. What's great about defaultPrevented
is that it stays with the event without needing to track track it globally!