Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add one event listener for all buttons

Tags:

javascript

How do I add an event listener to multiple buttons and get the value of each one depending on the one clicked. Eg:

<button id='but1'>
Button1
</button>
<button id='but2'>
Button2
</button>
<button id='but3'>
Button3
</button>
<button id='but4'>
Button4
</button>

So that on javascript, I wouldn't have to reference each button like:

Const but1 = document.getElementById('but1'); 
but1.addEventListener('click');
like image 823
amaugo somto Avatar asked Apr 05 '18 19:04

amaugo somto


People also ask

How do I add event listeners to multiple buttons?

Adding an Event Listener to Multiple Elements Using a for...of Loop + IIFE. Open the console and click any of the buttons. The same event listener is added to each button using a for...of loop along with an immediately invoked function that passes the current element of the loop back into the function.

Can I add event listener to all elements of class?

To add an event listener to all elements with class: Use the document. querySelectorAll() method to select the elements by class. Use the forEach() method to iterate over the collection of elements.

How do I add event listener only once?

We can pass an object as an argument to the addEventListener method and specify that the event is only handled once. This is achieved by passing the property once to the object. If we set once to true, the event will only be fired once.

Can you have more than one event listener?

The addEventListener() methodYou can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements.


1 Answers

You don't really need to add listeners to all the buttons. There is such thing in JS as Bubbling and capturing so you can wrap all your buttons with a div and catch all the events there. But make sure you check that the click was on a button and not on the div.

const wrapper = document.getElementById('wrapper');

wrapper.addEventListener('click', (event) => {
  const isButton = event.target.nodeName === 'BUTTON';
  if (!isButton) {
    return;
  }

  console.dir(event.target.id);
})
div {
  padding: 20px;
  border: 1px solid black;
}
<div id='wrapper'>
  <button id='but1'>
  Button1
  </button>
  <button id='but2'>
  Button2
  </button>
  <button id='but3'>
  Button3
  </button>
  <button id='but4'>
  Button4
  </button>
</div>
like image 73
Aliaksandr Sushkevich Avatar answered Oct 13 '22 08:10

Aliaksandr Sushkevich