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?


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.

const btns = document.querySelectorAll("button");
const controller = new AbortController();

btns.forEach((btn) => {
    () => {
    { signal: controller.signal }

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