1
I have the following question: How to optimize the script below? In total there are 14 clicks and each changes a certain ID. I don’t want to use jQuery.
Script that adds the listeners event:
document.getElementById("btn-1").addEventListener("click", function () {
myFunction(1);
});
document.getElementById("btn-2").addEventListener("click", function () {
myFunction(2);
});
document.getElementById("btn-3").addEventListener("click", function () {
myFunction(3);
});
document.getElementById("btn-4").addEventListener("click", function () {
myFunction(4);
});
Script that changes the styles according to the value passed:
function myFunction(a) {
if (a === 1) {
document.getElementById("cid-1").style.display = 'block';
document.getElementById("area-1").style.fill = '#dfdca3';
} else if (a === 2) {
document.getElementById("cid-2").style.display = 'block';
document.getElementById("area-2").style.fill = '#ed694b';
} else if (a === 3) {
document.getElementById("cid-3").style.display = 'block';
document.getElementById("area-3").style.fill = '#5fa7c8';
} else if (a === 4) {
document.getElementById("cid-4").style.display = 'block';
document.getElementById("area-4").style.fill = '#cce2e8';
}
}
Massa! already gives a "dry" in the codes. I will give a study in this stop delegating events. Valew msm!!
– DMiaguy
@Dmiaguy The great advantage of this over applying directly to the elements is that you do not need to use window.onload or Domcontentloaded and do not even check if the element exists, because it already circumvents all this, including whether to remove the element or need to use removeEventListener.
– Guilherme Nascimento