HomeSoftware DevelopmentJavaScript Occasion.defaultPrevented

JavaScript Occasion.defaultPrevented

Whether or not you began with the outdated on_____ property or addEventListener, that occasions drive person experiences in trendy JavaScript. If you happen to’ve labored with occasions, that preventDefault() and stopPropagation() are regularly used to deal with occasions. One factor you in all probability did not know: there is a defaultPrevented proptery on occasions!

Contemplate 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. Resulting from 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!

  • From Webcam to Animated GIF: the Secret Behind!
  • JavaScript Promise API

    Whereas synchronous code is less complicated to comply with and debug, async is usually higher for efficiency and adaptability. Why “maintain up the present” when you may set off quite a few requests without delay after which deal with them when every is prepared?  Guarantees are changing into a giant a part of the JavaScript world…


Most Popular

Recent Comments