-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path100-buttons-event-delegate.html
60 lines (46 loc) · 1.32 KB
/
100-buttons-event-delegate.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<head>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
gap: 2rem;
}
body button {
font-size: 20px;
}
</style>
</head>
<body>
<h2 id="display">not yet clicked</h2>
<button id="spawner">create one more button</button>
<main id="buttons"></main>
</body>
<script>
function handleButtonClick(e) {
const buttonId = e.target.id.split(' ')[1]
console.assert(Number.parseInt(buttonId) != Math.NaN, 'handleButtonClick received invalid button id')
displayNumber(buttonId)
}
function createButton(id, parent) {
const b = document.createElement('button')
b.style.margin = '.2rem'
b.innerText = `button ${id}`
parent.append(b)
b.id = b.innerText
}
function spawnButton() {
createButton(Math.floor(Math.random() * 100), document.querySelector('#buttons'))
}
function displayNumber(x) {
document.querySelector('#display').innerText = `button ${x}`
}
window.addEventListener('load', () => {
document.querySelector('#spawner').addEventListener('click', spawnButton)
document.querySelector('#buttons').addEventListener('click', handleButtonClick)
const buttonContainer = document.querySelector('#buttons')
for (let i = 0; i < 5; i += 1) {
createButton(i, buttonContainer)
}
})
</script>