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
    9 Mind-Blowing WebGL Demos

    As much as developers now loathe Flash, we're still playing a bit of catch up to natively duplicate the animation capabilities that Adobe's old technology provided us.  Of course we have canvas, an awesome technology, one which I highlighted 9 mind-blowing demos.  Another technology available...

  • By
    39 Shirts – Leaving Mozilla

    In 2001 I had just graduated from a small town high school and headed off to a small town college. I found myself in the quaint computer lab where the substandard computers featured two browsers: Internet Explorer and Mozilla. It was this lab where I fell...

Incredible Demos

  • By
    CSS :target

    One interesting CSS pseudo selector is :target.  The target pseudo selector provides styling capabilities for an element whose ID matches the window location's hash.  Let's have a quick look at how the CSS target pseudo selector works! The HTML Assume there are any number of HTML elements with...

  • By
    JavaScript Canvas Image Conversion

    At last week's Mozilla WebDev Offsite, we all spent half of the last day hacking on our future Mozilla Marketplace app. One mobile app that recently got a lot of attention was Instagram, which sold to Facebook for the bat shit crazy price of one...

Discussion

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