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 Canvas Demos

    The <canvas> element has been a revelation for the visual experts among our ranks.  Canvas provides the means for incredible and efficient animations with the added bonus of no Flash; these developers can flash their awesome JavaScript skills instead.  Here are nine unbelievable canvas demos that...

  • By
    Create a CSS Cube

    CSS cubes really showcase what CSS has become over the years, evolving from simple color and dimension directives to a language capable of creating deep, creative visuals.  Add animation and you've got something really neat.  Unfortunately each CSS cube tutorial I've read is a bit...

Incredible Demos

  • By
    MooTools Window Object Dumping

    Ever want to see all of the information stored within the window property of your browser? Here's your chance. The XHTML We need a wrapper DIV that we'll consider a console. The CSS I like making this look like a command-line console. The MooTools JavaScript Depending on what you have loaded...

  • By
    Select Dropdowns, MooTools, and CSS Print

    I know I've harped on this over and over again but it's important to enhance pages for print. You can do some things using simple CSS but today's post features MooTools and jQuery. We'll be taking the options of a SELECT element and generating...

Discussion

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