Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventListener with multiple elements [duplicate]

I started working with javascript. I have two buttons, and want change backgroundColor when click on any of these buttons. But my code doesn't work. This is my code:

document.getElementsByTagName("button").addEventListener("click", function(){
    func(this)
});

function func(element){
    element.style.backgroundColor="gray";
}
<div id="area">
    <button type="button" class="btn" id="btn1">Play With Me!</button>
    <button type="button" class="btn" id="btn2">Play With Me!</button>
</div>

is there any way that an addEventListener works with multiple elements?

like image 608
MO30 Qari Avatar asked May 19 '26 03:05

MO30 Qari


2 Answers

The best way is to have as few event listeners as possible in your code. So instead of attaching an event listener to each and every button, you can attach 1 single event listener to the area div and make suitable changes based on event.target attribute.

Run the below working code snippet:

document.getElementById('area').addEventListener('click', function(event) {
  func(event.target);
});

function func(element) {
  element.style.backgroundColor = "blue";
}
<div id="area">
  <button type="button" class="btn" id="btn1">Play With Me!</button>
  <button type="button" class="btn" id="btn2">Play With Me!</button>
</div>
like image 61
Adarsh Konchady Avatar answered May 20 '26 17:05

Adarsh Konchady


You could do it like this or DEMO

 var button = document.getElementsByTagName("button");
 for (var i = 0; i < button.length; i++) {
   button[i].addEventListener("click", function() {
     this.style.backgroundColor = "gray";
   });
 }
<div id="area">
  <button type="button" class="btn" id="btn1">Play With Me!</button>
  <button type="button" class="btn" id="btn2">Play With Me!</button>
</div>
like image 26
Nenad Vracar Avatar answered May 20 '26 15:05

Nenad Vracar