Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

eventlistener runs without clicking [duplicate]

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.

like image 354
Ender Ady Avatar asked Dec 06 '25 04:12

Ender Ady


2 Answers

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'))
like image 190
zfrisch Avatar answered Dec 08 '25 17:12

zfrisch


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');
like image 24
XCS Avatar answered Dec 08 '25 16:12

XCS