0
document.getElementById("hit").addEventListener("click",console.log('test'))

I have that line of code, hit is an id of a button : <button id = "hit" value="Hit">Hit</button> Refreshing the page outputs "test" in the console and i dont know why.

Ender Ady
  • 39
  • 8

3 Answers3

4

When you pass parameters to a function it is immediately called. You need to pass a function that will wait for the event and then call console.log with the specified parameters.

document.getElementById("hit").addEventListener("click",() => console.log('test'))
zfrisch
  • 8,474
  • 1
  • 22
  • 34
2

addEventListener("click",console.log('test')) will immediately run console.log('test') and pass the return value of console.log. The return value will be undefined, so your code is equivalent to this:

document.getElementById("hit").addEventListener("click", undefined);
console.log('test');

OR

const consoleReturnValue = console.log('test'); // will be undefined
document.getElementById("hit").addEventListener("click", consoleReturnValue );

I assume that what you are you trying to achieve is

addEventListener("click", () => console.log('this'));

Or, if you can't use ES6:

addEventListener("click", console.log.bind(window, 'this'));

In this case you actually pass a function as the second argument instead of the undefined primitve.


Fun fact, passing undefined as an argument is the same as not passing it, so your current addEventLinster call is the same as as:

document.getElementById("hit").addEventListener("click");
console.log('test');
XCS
  • 27,244
  • 26
  • 101
  • 151
0

In the event listener, using a function that takes parameters will automatically run the function, try this instead.

document.getElementById("hit").addEventListener("click", function (){ console.log('test'); });

Artanis
  • 561
  • 1
  • 7
  • 26
  • Welcome to Stack Overflow. Please read [How to Answer](https://stackoverflow.com/help/how-to-answer) so that you will see that good answers should explain what the problem was and how your suggestion solves the problem. Simply providing code is not a good answer and will likely get your answers down voted even if the code is correct. – Scott Marcus Oct 24 '18 at 21:21