0

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>

asked Sep 16, 2018 at 14:07
2
  • 1
    here addEventListener("click", guessLetter(x)) you're calling the function, and pass the (undefined) return value to addEventListener Commented Sep 16, 2018 at 14:10
  • You should get the value of the input in the guessLetter function Commented Sep 16, 2018 at 14:14

2 Answers 2

1

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);
});
answered Sep 16, 2018 at 14:16
Sign up to request clarification or add additional context in comments.

Comments

0

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);
}
answered Sep 16, 2018 at 14:17

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.