I have a JS function I’m trying to make into an event listener. I had help with a similar problem a while ago and have successfully converted a few functions since then.
This one is complicated by the fact that (a) there are variables that are used both within the function and outside it, and (b) there are 78 different id’s that can trigger the event. I have made a stab at it but I’m not sure how close I am to a solution…
HTML (from which I will remove the onclicks, and eventually the anchor tags altogether):
<li id="p0"><a href="#" onclick="choosecard(0);return false;"><img src="images/spacer.gif" alt="card0" height="99" width="66"></a></li>
<li id="p1"><a href="#" onclick="choosecard(1);return false;"><img src="images/spacer.gif" alt="card1" height="99" width="66"></a></li>
...
<li id="p77"><a href="#" onclick="choosecard(77);return false;"><img src="images/spacer.gif" alt="card77" height="99" width="66"></a></li>
Original JS:
function choosecard(cardno) {
if ( jobdone ) {
return;
} else {
document.getElementById('p'+cardno).innerHTML = '<img src="images/selected.jpg" alt="card selected">';
document.getElementById('f'+ns).value = cards[cardno];
ns++;
if ( ns == maxcards ) {
jobdone = true;
document.getElementById("showcards").disabled = false;
}
}
}
Revised JS:
var ns = 0;
var jobdone = false;
(function(){
var pcardno = 'p'+cardno;
var fns = 'f'+ns;
addEventListener('click', function() {
if ( jobdone ) {
return;
} else {
document.getElementById(pcardno).innerHTML = '<img src="images/selected.jpg" alt="card selected">';
document.getElementById(fns).value = cards[cardno];
ns++;
if ( ns == maxcards ) {
jobdone = true;
document.getElementById("showcards").disabled = false;
}
}
}, false);
})();