'What's better in terms of performance? Using addEventListener("click) in each element or add it to the document and differenciate them using e.target?
Just as I said in the title, I'm learning JS and I want my code to have the best performance possible. I saw a video in which the youtuber said that applying the addEventListener("click") to the document and using if statements to differenciate "how" activated the event is more effective and has a better performance than applying it individually
EXAMPLE
$document.addEventListener("click",(e)=>{
if (e.target.matches("nav i img")){
console.log("logrado");
if (hamburgerMenuState == false){
$hamburgerMenu.classList.add("left-zero");
$hamburgerMenu.classList.remove("left-away");
hamburgerMenuState = true;
}
else{
$hamburgerMenu.classList.remove("left-zero");
$hamburgerMenu.classList.add("left-away");
hamburgerMenuState = false;
}
}
else if(e.target.matches("#hamburger-menu ul li a")){
console.log("nahse")
$hamburgerMenu.classList.remove("left-zero");
$hamburgerMenu.classList.add("left-away");
hamburgerMenuState = false;
}
else if(e.target.matches("#seccion1 #iniciarReloj")){
$btnIniciarReloj.disabled = true;
intervalo = setInterval(()=>{
console.log(intervalo);
let fecha = new Date();
$document.getElementById("reloj").textContent = fecha.toLocaleTimeString();
},1000)
}
else if(e.target.matches("#seccion1 #detenerReloj")){
$btnIniciarReloj.disabled = false;
clearInterval(intervalo);
$document.getElementById("reloj").textContent = "";
}
else if(e.target.matches("#seccion1 #iniciarAlarma")){
audio.play();
}
else if(e.target.matches("#seccion1 #detenerAlarma")){
audio.pause();
audio.currentTime = 0;
}
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
