Software Development

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. In the event you’ve labored with occasions, you recognize that preventDefault() and stopPropagation() are continuously used to deal with occasions. One factor you most likely 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
        // 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 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 monitor it globally!

  • Animated 3D Flipping Menu with CSS
  • Write Simple, Elegant and Maintainable Media Queries with Sass
  • Simple Image Lazy Load and Fade

    One of many quickest and best web site efficiency optimizations is lowering picture loading.  Which means a wide range of issues, together with minifying pictures with instruments like ImageOptim and TinyPNG, utilizing knowledge URIs and sprites, and lazy loading pictures.  It’s kind of jarring whenever you’re lazy loading pictures they usually simply…

  • Chris Coyier: Some Amazing Work on CodePen III

What's your reaction?

Leave A Reply

Your email address will not be published. Required fields are marked *