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

164
Views
Should I add two event listeners to one single event?

I would like to two functions to one button. The first one will be added anyway while the second function depends on a true/false condition.

The following code works, but should I do something like this?

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript addEventListener()</h2>

<p>This example uses the addEventListener() method to attach a click event to a button.</p>

<button id="myBtn">Try it</button>

<p id="demo"></p>

<script>
document.getElementById("myBtn").addEventListener("click", displayDate);
document.getElementById("myBtn").addEventListener("click", test);

function displayDate() {
  document.getElementById("demo").innerHTML = Date();
}

function test() {
  document.getElementById("demo").innerHTML += "test";
}
</script>

</body>
</html> 
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can use condition

const btn = document.getElementById("myBtn");
let isEvent = true;

// Add 'Event'
btn.addEventListener("click", displayDate);

// Add conditional 'Event'
if (isEvent) {
    btn.addEventListener("click", test);
}

// OR
btn.addEventListener("click", e => {
    if (isEvent) {
        test(e);
    }
});

Notice: Do not forget to remove event

about 4 years ago · Juan Pablo Isaza Report

0

To solve your problem I would make 1 function with a function within that makes the decision for your condition.

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!