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

  • By
    Page Visibility API

    One event that's always been lacking within the document is a signal for when the user is looking at a given tab, or another tab. When does the user switch off our site to look at something else? When do they come back?

  • By
    Convert XML to JSON with JavaScript

    If you follow me on Twitter, you know that I've been working on a super top secret mobile application using Appcelerator Titanium.  The experience has been great:  using JavaScript to create easy to write, easy to test, native mobile apps has been fun.  My...

Incredible Demos

  • By
    Using Opacity to Show Focus with MooTools

    I'm a huge fan of using subtle effects like link nudging (jQuery, MooTools) to enhance the user experience and increase the perceived dynamism of my websites. Trust me -- a lot of little things are what take websites to the next level.

  • By
    MooTools History Plugin

    One of the reasons I love AJAX technology so much is because it allows us to avoid unnecessary page loads.  Why download the header, footer, and other static data multiple times if that specific data never changes?  It's a waste of time, processing, and bandwidth.  Unfortunately...

Discussion

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