Javascript click event listener on class
Attach a click
event to multiple elements with the same class employing querySelectorAll
and addEventListener
:
This small script fetches each element with .class-name
and assigns a click listener
to all of them. Upon being clicked, the said element is logged into the console.
Catering to Dynamic Content: Event Delegation
In the real world of web apps, dynamic elements often come into play. The task is to cater to clicks on new elements without re-attaching listeners every time an element is added. This is where Event Delegation plays a crucial role:
This code attaches just one listener to the document.body
and checks for .dynamic-class
each time any element is clicked. It's efficient and tidy.
Avoiding Duplication of Event Listeners
Beware of the multiplication trick of event listeners! Ensuring each event listener is added only once will help you avoid surprises:
By firstly removing any existing listeners before setting up new ones, this function ensures no duplication of listeners.
Safe Iteration: Converting Collections to Arrays
Given getElementsByClassName
returns a live HTMLCollection
, to ensure a safe iteration - just turn it into an array:
Prioritizing Cross-Browser Compatibility
Both getElementsByClassName
and querySelectorAll
return a list of elements but have distinctions in compatibility. For catering to older browsers, querySelectorAll
gets an edge:
Remain mindful of these intricacies to avoid unpleasant surprises in certain browser environments.
Leveling Up Event Handling With Event Target
In event handling, event.target
serves as the breadcrumb in the labyrinth for checking if the event targets our very element:
With event.target.closest()
, you make sure you're not lost even if a click occurs on a child element.
Ensure Compatibility & Performance
Balance between graceful degradation and progressive enhancement to boost cross-browser compatibility in JavaScript:
By verifying feature availability, we can bestow a consistent, smooth experience to users.
Embrace the Present With Modern JavaScript
Modern JavaScript provides an easy way to iterate over collections:
The for...of
loop is a simple, effective iteration method that works on NodeList
s returned by querySelectorAll
.
Was this article helpful?