Whether you started with the old on_____
property or addEventListener
, you know that events drive user experiences in modern JavaScript. If you’ve worked with events, you know that preventDefault()
and stopPropagation()
are frequently used to handle events. One thing you probably didn’t know: there’s a defaultPrevented
proptery on events!
Consider the following block of code:
// Specific to a link const link = document.querySelector('#my-link'); link.addEventListener('click', e => e.preventDefault()); // A larger document scope document.addEventListener('click', documentClickHandler); function documentClickHandler(event) { if (event.defaultPrevented) {// Using the property // Do one thing if the click has been handled } else { // Otherwise do something fresh } }
When preventDefault
is called on a given event, the defaultPrevented
property gets toggled to true
. Due to event propagation, the event bubbles upward with this defaultPrevented
value.
I’ve been handling events for two decades and didn’t know this property existed until now. What’s great about defaultPrevented
is that it stays with the event without needing to track track it globally!
Page Visibility API
One event that’s always been lacking within the document is a signal for when the user is looking at a given tab, or another tab. When does the user switch off our site to look at something else? When do they come back?
CSS Animations Between Media Queries
CSS animations are right up there with sliced bread. CSS animations are efficient because they can be hardware accelerated, they require no JavaScript overhead, and they are composed of very little CSS code. Quite often we add CSS transforms to elements via CSS during…
CSS @supports
Feature detection via JavaScript is a client side best practice and for all the right reasons, but unfortunately that same functionality hasn’t been available within CSS. What we end up doing is repeating the same properties multiple times with each browser prefix. Yuck. Another thing we…
MooTools Overlay Plugin
Overlays have become a big part of modern websites; we can probably attribute that to the numerous lightboxes that use them. I’ve found a ton of overlay code snippets out there but none of them satisfy my taste in code. Many of them are…
Source link