so this is noobie .. but i am trying to complete a challenge with more due diligence than just downloading the answer,
my current html code is:
JavaScript
x
30
30
1
<!DOCTYPE html>
2
<html lang="en" dir="ltr">
3
4
<head>
5
<meta charset="utf-8">
6
<title>Drum Kit</title>
7
<link rel="stylesheet" href="styles.css">
8
<link href="https://fonts.googleapis.com/css?family=Arvo" rel="stylesheet">
9
</head>
10
11
<body>
12
13
<h1 id="title">Drum 🥁 Kit</h1>
14
<div class="set">
15
<button class="w drum">w</button>
16
<button class="a drum">a</button>
17
<button class="s drum">s</button>
18
<button class="d drum">d</button>
19
<button class="j drum">j</button>
20
<button class="k drum">k</button>
21
<button class="l drum">l</button>
22
</div>
23
24
25
<footer>
26
Made with ❤️ in London.
27
</footer>
28
<script src="index.js" charset="utf-8"></script>
29
</body>
30
my javascript codes :
JavaScript
1
8
1
document.querySelector("button").addEventListener("click", handleClick);
2
function handleClick() {
3
alert("I got clicked!");
4
}
5
6
7
document.querySelectorAll(".drum")[1, 2, 3, 4, 5, 6].addEventListener("click", handleClick);
8
essentially, the current code is running the event listener for the first and last item of the array only, trying to add it to all 6 but am stuck
thanks to all
Advertisement
Answer
Instead of attaching listeners to each button, add one to the container (set
) and, using event delegation, let that listener capture all the events that “bubble up” the DOM from its child elements, and call a function.
JavaScript
1
9
1
const set = document.querySelector('.set');
2
set.addEventListener('click', handleClick, false);
3
4
function handleClick(e) {
5
if (e.target.matches('button')) {
6
const { textContent } = e.target;
7
console.log(`Banging the ${textContent} drum!`);
8
}
9
}
JavaScript
1
13
13
1
<h1 id="title">Drum 🥁 Kit</h1>
2
<div class="set">
3
<button class="w drum">w</button>
4
<button class="a drum">a</button>
5
<button class="s drum">s</button>
6
<button class="d drum">d</button>
7
<button class="j drum">j</button>
8
<button class="k drum">k</button>
9
<button class="l drum">l</button>
10
</div>
11
<footer>
12
Made with ❤️ in London.
13
</footer>
Additional documentation