Efficiently trigger event
Avoid creating tons of events in JavaScript
Imagine wanting to add an onclick event to all the elements with a class "js-class-of-item" in a page, it could be done using a loop but this way there will be X events created slowing the performance. A solution is creating an event handler to the parent and there check what has been clicked avoiding loops, the parent could be the body:
document.body.addEventListener('click', function (event) {
if (event.target.classList.contains('js-class-of-item')) {
const item = event.target
// do whatever with item
// ...
}
})
or a more specific area:
document
.getElementById('specific-area')
.addEventListener('click', function (event) {
if (event.target.classList.contains('js-class-of-item')) {
const item = event.target
// do whatever with item
// ...
}
})