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
    Creating Scrolling Parallax Effects with CSS

    Introduction For quite a long time now websites with the so called "parallax" effect have been really popular. In case you have not heard of this effect, it basically includes different layers of images that are moving in different directions or with different speed. This leads to a...

  • By
    Being a Dev Dad

    I get asked loads of questions every day but I'm always surprised that they're rarely questions about code or even tech -- many of the questions I get are more about non-dev stuff like what my office is like, what software I use, and oftentimes...

Incredible Demos

  • By
    Generate Dojo GFX Drawings from SVG Files

    One of the most awesome parts of the Dojo / Dijit / DojoX family is the amazing GFX library.  GFX lives within the dojox.gfx namespace and provides the foundation of Dojo's charting, drawing, and sketch libraries.  GFX allows you to create vector graphics (SVG, VML...

  • By
    MooTools Gone Wild: Element Flashing

    If you're like me and lay awake in bed at night, you've flipped on the TV and seen the commercials: misguided, attention-starved college girls fueled by alcohol ruining their futures by flashing lame camera-men on Spring Break. Why do they do it? Attention...

Discussion

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