Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

267
Views
addEventListener with if condition not working

I am trying to make a button that triggers the <p> element to be changed from Boing! to Bummtschak!

When the page loads Bummtschak! is displayed, although I did not click and nothing happens in the following click event. I do not know what I am doing wrong.

const para = document.querySelector("p");
const btn = document.getElementById("btn");

btn.addEventListener('click', backTo());
function backTo() {
   if (para.textContent == "Boing!") {
       para.textContent = "Bummtschak!";
   }else{
       para.textContent = "Bummtschak!";
   }
}

The html is:

...
<script src="script.js" defer></script>
</head>
<body>
    <button id="btn"></button>
    <p>Boing!</p>
</body>
</html>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You should not have the () in the addEventListener

const para = document.querySelector("p");
const btn = document.getElementById("btn");

btn.addEventListener('click', backTo);
function backTo() {
   if (para.textContent == "Boing!") {
       para.textContent = "Bummtschak!";
   }else{
       para.textContent = "Bummtschak!";
   }
}
   <button id="btn"></button>
    <p>Boing!</p>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!