For readability sake, I wanted to declare a function and call it in the addEventListener’s second parameter but that didn’t work. Then, I used an anonymous function and it worked just fine. Why? Here’s my original without an anonymous function:
const checkInputFunc = function () {
const userInputNum = document.querySelector("#your-guess").value;
if (!userInputNum) {
displayInputStatusMessage("Please insert a number");
} else if (userInputNum > correctNum) {
displayInputStatusMessage("Too high...");
} else if (userInputNum < correctNum) {
displayInputStatusMessage("Too low...");
} else {
displayInputStatusMessage("Correct!");
}
};
document.querySelector("#clickButton").addEventListener("click", checkInputFunc())
And here’s the one with it:
document.querySelector("#clickButton").addEventListener("click", function () {
const userInputNum = document.querySelector("#your-guess").value;
if (!userInputNum) {
displayInputStatusMessage("Please insert a number");
} else if (userInputNum > correctNum) {
displayInputStatusMessage("Too high...");
} else if (userInputNum < correctNum) {
displayInputStatusMessage("Too low...");
} else {
displayInputStatusMessage("Correct!");
}
});
If you add the parenthesis after it then the function is called no matter what . That’s what the parenthesis do: they call the function. You only want the function called after the ‘click’ happens…so don’t include the parens. Let the ‘click’ event trigger it.