Home > Mobile >  Onclick only executing function once
Onclick only executing function once

Time:10-27

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>

CodePudding user response:

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

CodePudding user response:

You have to use this:

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

CodePudding user response:

I hope this will help you try this:

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