JavaScript Occasion.defaultPrevented


Whether or not you began with the outdated on_____ property or addEventListener, you recognize that occasions drive consumer experiences in fashionable JavaScript. In the event you’ve labored with occasions, you recognize that preventDefault() and stopPropagation() are steadily used to deal with occasions. One factor you most likely did not know: there is a defaultPrevented proptery on occasions!

Think about the next block of code:

// Particular to a hyperlink
const hyperlink = doc.querySelector('#my-link');
hyperlink.addEventListener('click on', e => e.preventDefault());

// A bigger doc scope
doc.addEventListener('click on', documentClickHandler);
operate documentClickHandler(occasion) {
    if (occasion.defaultPrevented) {// Utilizing the property
        // Do one factor if the press has been dealt with
    }
    else {
        // In any other case do one thing recent
    }
}

When preventDefault is known as on a given occasion, the defaultPrevented property will get toggled to true. As a consequence of occasion propagation, the occasion bubbles upward with this defaultPrevented worth.

I have been dealing with occasions for twenty years and did not know this property existed till now. What’s nice about defaultPrevented is that it stays with the occasion without having to trace monitor it globally!

  • CSS vs. JS Animation: Which is Faster?

    How is it attainable that JavaScript-based animation has secretly all the time been as quick — or quicker — than CSS transitions? And, how is it attainable that Adobe and Google persistently launch media-rich cell websites that rival the efficiency of native apps? This text serves as a point-by-point…

  • Responsive Images: The Ultimate Guide

    Likelihood is that any Internet designers utilizing our Ghostlab browser testing app, which permits seamless testing throughout all units concurrently, can have labored with responsive design in some form or type. And as as we speak’s web sites and units change into ever extra diversified, a plethora of responsive photographs…

  • 9 Mind-Blowing WebGL Demos

    As a lot as builders now detest Flash, we’re nonetheless enjoying a little bit of catch as much as natively duplicate the animation capabilities that Adobe’s outdated know-how supplied us.  After all we’ve got canvas, an superior know-how, one which I highlighted 9 mind-blowing demos.  One other know-how out there…

  • Multiple File Upload Input

    Most of the time, I discover myself eager to add multiple file at a time.  Having to make use of a number of “file” INPUT components is annoying, sluggish, and inefficient.  And if I hate them, I can not think about how aggravated my customers can be.  Fortunately Safari, Chrome…


Leave a Comment