I found a javascript tutorial in which a coder seems to handle click events by an alternative approach.
- Place an eventlistener for clicks on the body
- Give all elements inside the body a specific data-element attribute (additional data-attributes may be required to specify the exact element)
- Place a switch inside of the body-eventlistener and let it check for e.target.dataset.element
- Execute code based on the data-element attribute
This can look like this (simplified):
document.addEventListener("DOMContentLoaded", () => {
document.body.addEventListener("click", e => {
e.preventDefault();
switch (e.target.dataset.element) {
case "navigation":
console.log("a navbutton was clicked")
case "something":
console.log("something was clicked")
}
});
});
Do you think this can lead to better performance? No more than 1 eventlistener for clicks are neccessary by this approach. There is even space for other improvements like no need for the usage of buttons (p tags could handle things), and so, and so…
Love to get your opinion to it.
Best regards