document.querySelector('#rock').addEventListener('click', game(1));
function game(input){
console.log(input);
}
game function should be called when I click on the block with id rock, but game function executing without even calling it . What the hell is going on .
You are calling the function game(1), the parentheses () are used to invoke a function.
Not sure what the argument 1 is supposed to help with but it doesn’t seem useful to have the value of 1 hardcoded in the function call. Can you please post the full code or a live version so we can get some context to what you are trying to do?
Actually I want when I click on #rock then game() function is called with argument 1. Why In the first code the game function executes without triggering the event. While the second code works fine .
This creates an anonymous function that will callback the game(); function with the parameter value of 1 when the element is clicked.
As of why your code runs before is still a question… We can’t really help that much with only this little amount of code information. Can you maybe give us more part of your code so that we can try to troubleshoot what’s wrong with your code, because currently, We don’t even know where the 1 comes from, and the context of it is.
No, it will call the function when the page first loads, not when the click event is fired.
The addEventListener method is expecting a callback function, that is just the function definition so it can call it on your behalf when the element the handler is attached to is clicked. If you use () you are just calling the function.
// called on page load
document.querySelector('#rock').addEventListener('click', game(1));
// called when the event is triggered
document.querySelector('#rock').addEventListener('click', game);
Edit: That is why I asked for some context, I’m trying to figure out what the 1 is used for.
<div id="rock">test</div>
function test(one) {
console.log(one) // logs 1 when the #rock element is clicked
}
document.querySelector('#rock').addEventListener('click', () => test(1));
As @lasjorg said, MDN Web Docs is the best resource for Web Development. I used a different one, that is basically the same, but I just like that it’s a web app.