Friday, October 7, 2022
HomeSoftware DevelopmentJavaScript Occasion.defaultPrevented

JavaScript Occasion.defaultPrevented


Whether or not you began with the previous on_____ property or addEventListener, you recognize that occasions drive person experiences in trendy JavaScript. When you’ve labored with occasions, you recognize that preventDefault() and stopPropagation() are incessantly 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 named 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 while not having to trace observe it globally!

  • Designing for Simplicity

    Earlier than we get began, it is price me spending a short second introducing myself to you. My title is Mark (or @integralist if Twitter occurs to be your communication instrument of alternative) and I at present work for BBC Information in London England as a principal engineer/tech…

  • From Webcam to Animated GIF: the Secret Behind chat.meatspac.es!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments