xxxxxxxxxx
Explain event delegation :
“Js event listeners fire not only on a single DOM element
but on all its descendents”
The idea is that if we have a lot of elements handled in a
similar way, then instead of assigning a handler to each of
them – we put a single handler on their common ancestor.
xxxxxxxxxx
Event Delegation is basically a pattern to handle events efficiently. Instead of adding an event listener to each and every similar element, we can add an event listener to a parent element and call an event on a particular target using the .target property of the event object.
xxxxxxxxxx
selector = ".buttonClass";
document.getElementById('buttons').addEventListener('click', event => { // Step 2
if (event.target.matches(selector)) {
console.log('Click!');
}
})
xxxxxxxxxx
//Event delegation is a technique for listening to events where you delegate a parent element as the listener for all of the events that happen inside it.
//For example, if you wanted to detect field changes in inside a specific form, you can use event delegation technique,
var form = document.querySelector("#registration-form");
// Listen for changes to fields inside the form
form.addEventListener(
"input",
function (event) {
// Log the field that was changed
console.log(event.target);
},
false
);