JavaScript event listener on multiple items

how can I add an event listener to an array of objects and allow only one item to fire an event while the others don’t in vanilla Javascript … Let’s say I have 5 buttons and I have used document.querySelectorAll to get all the buttons into an array and I want a scenario where when a user clicks on a button, the user won’t be able to click on the other 4 buttons… Is it feasible?

Hello!

Yes, use the addEventListener("click", functionName) to every button and then use removeEventListener("click", functionName) on every other button once one has been clicked, like this.

1 Like

You could also add the attribute disabled to each of the other buttons that weren’t clicked.

It worked… Thank you :pray:

1 Like

I don’t think I have ever used this method, but you can also use an an abortable listener.

<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
const btns = document.querySelectorAll("button");
const controller = new AbortController();

btns.forEach((btn) => {
  btn.addEventListener(
    "click",
    () => {
      console.log("clicked");
      controller.abort();
    },
    { signal: controller.signal }
  );
});
2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.