Im trying to make a gaming website in which when the user first signs in, they are greeted by two show lights that shine down on words that say: "WELCOME TO COSMIC GAMES!" I want to make it interactive, so I’ve been trying to make it so that when the user clicks anywhere on the document, it displays one of the words. I already got the first word, the problem, though is trying to call the second function to light up the second word without calling the first function.
This is what I tried:
var clicks = 0;
function playLightSwitch1() {
clicks = 1;
audio = new Audio("lightSwitch.mp3");
audio.play();
document.getElementById("welcomeText").setAttribute("class", "glowWelcome");
document.getElementById("whiteTraingle1").setAttribute("class", "whiteTraingleVisible1");
document.getElementById("whiteTraingle2").setAttribute("class", "whiteTraingleVisible2");
}
if (clicks == 0) {
document.addEventListener("click", playLightSwitch1);
}
if (clicks = 1) {
document.removeEventListener("click", playLightSwitch1);
}
the first function worked, but when I clicked again, the first function ran. I just want nothing to happen on the second click. PS: ignore the setAttribute
stuff, that’s just changing the text so it glows.
2
Answers
Instead of dynamically adding/removing event handlers, a better approach to achieve your goal would be to have a single event handler which iterates through a set of actions on each click.
You can place these actions inside an array and execute each one based on an index which increments as the document (or whatever target element you require) is clicked.
Here’s a working example:
A few things to note in this implementation:
addEventListener()
instead of addingonclick
attributes to the DOM.classList.add()
instead of updatingclass
attributes.audio
element when the DOM loads, instead of re-creating it every time the event fires.There are some logical problems in your code.
I provide updated code. Hope it helps you.