const anchor1El = document.getElementById('a1')
const anchor2El = document.getElementById('a2')
if (anchor1El.addEventListener('click', function onefn() {
alert('link 1 was clicked')
}));
else
if(anchor2El.addEventListener('click', function twofn() {
alert("link 2 was clicked")
}));
both of these anchors are in different HTML pages, what I can't wrap my head around is why the first alert is shown, be it which ever it is:
const anchor1El = document.getElementById('a1')
const anchor2El = document.getElementById('a2')
if(anchor2El.addEventListener('click', function fntwo() {
alert("link 2 was clicked")//only this is shown
}));
else
if (anchor1El.addEventListener('click', function fnone() {
alert('link 1 was clicked')//but this isn't shown
}));
I've tried using let instead of const, and I even tried using onclick. But none of these alternatives slved my problem. Does anybody know what is wrong?
CodePudding user response:
if you use if else then, it will mean that if the first is true,
it won't run the second checking.
so use 2 if
and now should work in every case!
also, you don't need to wrap the entire event listener inside if
is enough only the element,
if the element is present on the DOM, if it will be true and add an event listener to that element
if the element isn't in the DOM with the if()
we prevent the error, and it will not break our script.
// elements
const anchor1El = document.getElementById('a1');
const anchor2El = document.getElementById('a2');
// functions
const fnone = () => alert('link 1 was clicked');
const fntwo = () => alert('link 2 was clicked');
// events
if (anchor1El) anchor1El.addEventListener("click", fnone);
if (anchor2El) anchor2El.addEventListener("click", fntwo);
<button id="a1">a1</button>
<!--<button id="a2">a2</button>-->