Boomblaster Dani
Boomblaster Dani

Reputation: 1

Onclick only executing function once

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>

Upvotes: 0

Views: 220

Answers (3)

Shoaib Amin
Shoaib Amin

Reputation: 205

I hope this will help you try this:

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

Upvotes: 0

Usitha Indeewara
Usitha Indeewara

Reputation: 1023

You have to use this:

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

Upvotes: 0

David
David

Reputation: 219077

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">

Upvotes: 3

Related Questions