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.
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.
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'))
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');
document.getElementById("hit").addEventListener("click", function (){
console.log('test');
});