user16971617
user16971617

Reputation: 535

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> 

Upvotes: 0

Views: 77

Answers (2)

Ryan M.
Ryan M.

Reputation: 1

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

Upvotes: 0

Ali Yaghoubi
Ali Yaghoubi

Reputation: 1280

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

Upvotes: 1

Related Questions