Console.log show result only once and the button don't work when addEventListener

Viewed 273

I know this is a basic problem, but I don't know to fix it!
In part of my code, I have the same block of code as below; that part works okay, but for this part I'm getting an error!

console.log is only showing result for the first time only!

const bt = document.createElement('button');
bt.innerHTML = "CLICK HERE";
document.querySelector('#dv').append(bt);

bt.addEventListener('click', console.log('clicked'));
<!DOCTYPE html>
<html>
    <head>
        <title>test</title>
        <script src="test.js" defer></script>
    </head>
    <body>
        <div id="dv"></div>
    </body>
</html>
3 Answers

You need to wrap your event callback code in a function example

const bt = document.createElement('button');
bt.innerHTML = "CLICK HERE";
document.querySelector('#dv').append(bt);

bt.addEventListener('click', () => console.log('clicked'));

You are executing it immediately. Make a function as you add the eventListener.

const bt = document.createElement('button');
bt.innerHTML = "CLICK HERE";
document.querySelector('#dv').append(bt);

bt.addEventListener('click', function() {
  console.log('clicked')
});
<!DOCTYPE html>
<html>

<head>
  <title>test</title>
</head>

<body>
  <div id="dv"></div>
</body>

</html>

You need to attach the click event using addEventListener as below.

const bt = document.createElement('button');
bt.innerHTML = "CLICK HERE";
document.querySelector('#dv').append(bt);

bt.addEventListener('click', () => console.log('clicked'));
<!DOCTYPE html>
<html>
    <head>
        <title>test</title>
    </head>
    <body>
        <div id="dv"></div>
    </body>
</html>

Related