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?
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With