JavaScript Event.defaultPrevented

By  on  

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!

Recent Features

Incredible Demos

  • By
    Digg-Style Dynamic Share Widget Using the Dojo Toolkit

    I've always seen Digg as a very progressive website. Digg uses experimental, ajaxified methods for comments and mission-critical functions. One nice touch Digg has added to their website is their hover share widget. Here's how to implement that functionality on your site...

  • By
    Check All/None Checkboxes Using MooTools

    There's nothing worse than having to click every checkbox in a list. Why not allow users to click one item and every checkbox becomes checked? Here's how to do just that with MooTools 1.2. The XHTML Note the image with the ucuc ID -- that...

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!