Omer
Omer

Reputation: 163

addEventListener - the function execute before it is called

I'm learning JavaScript's Event-listener. This is my code:

var x = 0;

document.getElementById("myBtn").addEventListener("click", myFunction);

function myFunction() {
    x++;
    document.getElementById('para').innerHTML = x ;
}

This is the HTML:

<body>
  <h1>Headline</h1>
  <button id="myBtn" onclick="myFunction()">Click</button>
  <p id="para">Some text</p>
  <script src="JS.js"></script>
</body>

The issue is that myFunction() is called both when the page is loaded AND when I click on the button. Why is that and how do I fix it? I tried to put the script in the HTML's head but then it gives me an error because the button element isn't yet loaded.

Upvotes: 1

Views: 671

Answers (1)

Harsh Patel
Harsh Patel

Reputation: 6830

Hope this will help you

var x = 0;

document.getElementById("myBtn").addEventListener("click", myFunction);

function myFunction() {
    x++;
    document.getElementById('para').innerHTML = x ;
    console.log(x)
}
<body>
  <h1>Headline</h1>
  <button id="myBtn">Click</button>
  <p id="para">Some text</p>
</body>

Because you're calling function twice when you click for the first time

Upvotes: 1

Related Questions