JavaScript Occasion.defaultPrevented


Whether or not you began with the outdated on_____ property or addEventListener, you realize that occasions drive consumer experiences in fashionable JavaScript. When you’ve labored with occasions, you realize that preventDefault() and stopPropagation() are ceaselessly 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);
perform documentClickHandler(occasion) {
    if (occasion.defaultPrevented) {// Utilizing the property
        // Do one factor if the clicking 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. Because of occasion propagation, the occasion bubbles upward with this defaultPrevented worth.

I have been dealing with occasions for 20 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 observe it globally!

  • How to Create a Twitter Card
  • Create a Sheen Logo Effect with CSS


Please enter your comment!
Please enter your name here