Solution 1 :

This doesn’t do what you think it does:

btn1.onclick = console.log('hey');

This executes console.log('hey') immediately, then sets its result (which is undefined) to btn1.onclick;

What you want is a function to assign as the click handler. Also, use addEventListener instead of assigning to onclick. For example:

let btn1 = document.getElementById("btn1");
btn1.addEventListener('click', () => console.log('hey'));
<input value="test" type="button" id="btn1" data="onclick">

Or, using the more explicit function syntax for potential clarity:

let btn1 = document.getElementById("btn1");
btn1.addEventListener('click', function () {
  console.log('hey');
});
<input value="test" type="button" id="btn1" data="onclick">

Solution 2 :

You have to use this:

btn1.onclick = () => console.log('hey');

Solution 3 :

I hope this will help you try this:

    let btn1 = document.getElementById("btn1");
    btn1.addEventListener('click', () => console.log('hey'));

Problem :

So I’m pretty new to js. I’ve tried to make a button that logs hey in the console, but it already logs it before clicking the button. And when clicking the button it won’t do anything. This is my code.

let btn1 = document.getElementById("btn1");
btn1.onclick = console.log('hey');
<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
   </head>
   <body>
      <input value="test" type="button" id="btn1" data="onclick">
   </body>
</html>

Comments

Comment posted by caTS

You need to set it to a function:

Comment posted by addEventListener(“click”,…) firing immediately

Does this answer your question?

By