I wonder why this guessLetter function will automatically called during my page load. It suppose to be invoke after user press the button. Can someone help me to spot the error? Thanks a lot.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<input type="text" id="guessLetter" /><input id="btn" type="button" value="Enter" />
<script>
var wordLetters = ['G', 'O', 'A', 'T'];
var guessedLetters = ['_', '_', '_', '_'];
function guessLetter(letter) {
console.log('2');
}
var x = document.getElementById('guessLetter').value;
document.getElementById('btn').addEventListener("click", guessLetter(x));
</script>
</body>
</html>
2 Answers 2
That is because function will be called directly when the javascript code is executed as you have added parenthesis.
I guess, you can achieve what you want by replacing the addEventListener code by
var x = document.getElementById('guessLetter').value;
document.getElementById('btn').addEventListener("click", function() {
guessLetter(x);
});
Comments
The problem is with this line
document.getElementById('btn').addEventListener("click", guessLetter(x));
You are calling the function instead attach it to the event listeners
Replace the call with
document.getElementById('btn').addEventListener("click", guessLetter);
And instead of sending the parameter, try to read it inside the function. Something like:
function guessLetter() {
var x = document.getElementById('guessLetter').value;
console.log(x);
}
addEventListener("click", guessLetter(x))you're calling the function, and pass the (undefined) return value toaddEventListenerguessLetterfunction