So I have a function, that is called "inGame()" and right after creating the function I let JavaScript create a button with the onClick-Event "inGame()". But when I click the button the console tells me
Uncaught ReferenceError: inGame is not defined at HTMLButtonElement.onclick (index.html:1)
(index.html:1 is <!DOCTYPE html>
...)
This is the code I am working with:
var i = 0;
function inGame() {
try {
removeElement("nextPlayer");
} catch (e) {/*First time the function gets called -> Button doesn't exist yet*/}
document.getElementById("title").innerText = players[i] + " ist dran!"; //Just a title, don't worry
rollDice(i);
i++;
if (i == players.length) {i = 0;}
}
inGame();
setTimeout(addElement("game", "button", "nextPlayer", "Nächster Spieler"), 2000);
setTimeout(document.getElementById("nextPlayer").classList.add("btn"), 2000);
setTimeout(document.getElementById("nextPlayer").classList.add("btn-success"), 2000);
setTimeout(document.getElementById("nextPlayer").setAttribute("onClick", "inGame()"), 2000);
BTW: The reason I am not using a for-loop but a function is, that I want the loop to wait until a button is pressed to continue with the next round.
EDIT: Some general information about the code. I am using the standard html-Framework Visual Studio Code gives you, when you type an exclamation-mark into an emtpy HTML-file and press enter.
The script is in the head-tag, I also tried to put it in the body but nothing changed.
I am using a Button-Tag (<button>
) since Bootstrap used a button-tag in it's examples. I changed it to a div but it didn't change anything so I am back at a button.
It's not the first time in the code where I add the onClick-event via attributes. addElement("content", "button", "Play", "Spielen"); document.getElementById("Play").setAttribute("onclick", "Play()");
This is the addElement-Function:
function addElement(parentId, elementTag, elementId, html) {/*CODE*/}