LearningJS888 LearningJS888 - 5 months ago 7
HTML Question

Trigger function on click for hangman game

I'm new to JavaScript and have been trying to code up this Hangman game, but am running into issues. What I have to far is the following:

My HTML:

<div class="col-md-4">
<div id="placeHolder">_ _ _ _ _ _</div>
<div id="gamestatus"></div>
<input type="text" size="1" id="letterGuess" maxlength="1">
<button id="button" onclick="guess()">Press to start</button>
</div>


My JavaScript:

var dictionary = ['music', 'mountain', 'forest', 'florida', 'sweden', 'golf'];
var wordUsed, input, placeHolder;

function startGame()
{
placeHolder = "";
var totalGuesses = 10;
wordUsed = dictionary[Math.floor(Math.random() * dictionary.length)];
console.log(wordUsed);

var buttonText = document.getElementById("button").innerHTML = "Guess";

for(var i = 0; i < wordUsed.length; i++)
{
placeHolder += "_ ";
}

document.getElementById("placeHolder").innerHTML = placeHolder;
document.getElementById("gamestatus").innerHTML = "Game is in progress.";

}

function guess()
{
var correctGuess = false;
var ip = document.getElementById("letterGuess");
input = ip.value;

for(var i = 0; i < wordUsed.length; i++)
{
if(input == wordUsed.substring(i, i + 1))
{
correctGuess = true;
placeHolder = placeHolder.substring(0, i) + input + placeHolder.substring(i + 1, placeHolder.length + 1);
document.getElementById("placeHolder").innerHTML = placeHolder;
}
}
if(!correctGuess)
{
totalGuesses--;
}
if(placeHolder == wordUsed)
{
alert("You WIN!");
}
if(totalGuesses == 0)
{
alert("You LOSE!")
startGame();
}
}
startGame();
document.getElementById("button").onclick = guess;


So the code is correctly selecting a word and placing the correct amount of underscores in places of the letters; but nothing happens when I run my code. I might've over-looked something really simple and would really appreciate if someone could point out what is wrong with the code/logic.

Also, any other tips on how to improve the code/logic will be appreciated! Thanks.

Answer

The last line in your code:

document.getElementById("button").onclick = letterGuess;

You have not declared letterGuess() as a function. You probably want something like this:

document.getElementById("button").addEventListener("click", guess);

This will execute your guess() function on every click on the Button. In addition you can/should remove the onclick="" attribute from the <button>

Here is a jsfiddle that works. Is your html set up correctly and do you actually load the script?

Your html should look something like this:

<!DOCTYPE html>
<html>
<head></head>

<body>
    <!-- your game html -->
    <script type="text/javascript" src="game.js"></script>
</body>
</html>

If letterGuess was just a typo, please console.log() something in your guess() function, to make sure it's being executed after clicking the button.

Comments