-
Notifications
You must be signed in to change notification settings - Fork 0
/
EventDelegation_Demo.html
56 lines (41 loc) · 1.24 KB
/
EventDelegation_Demo.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
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Event Bubbling and Delegation</h1>
<p>Open console and click Item or ClassA to see results.</p>
<ul id="parent-elem">
<li id="child-1">Item 1</li>
<li id="child-2">Item 2</li>
<li id="child-3">Item 3</li>
<li id="child-4">Item 4</li>
<li id="child-5">Item 5</li>
<li id="child-6">Item 6</li>
</ul>
<div id='parentDiv'>
<a class="childA">ClassA</a><br>
<a class="childB">ClassB</a><br>
<a class="childC">ClassC</a><br>
</div>
<script>
// Get the element, add a click listener...
document.getElementById("parent-elem").addEventListener("click", function(e) {
// e.target is the clicked element!
// If it was a list item
if(e.target && e.target.nodeName == "LI") {
// List item found! Output the ID!
console.log("Children elem ", e.target.id.replace("child-", ""), " was clicked!");
}
});
// Get the parent DIV, add click listener...
document.getElementById("parentDiv").addEventListener("click",function(e) {
// e.target was the clicked element
if (e.target && e.target.matches("a.childA")) {
//console.log("Anchor element clicked!");
console.dir(e.target.classList);
console.log(e.target);
console.log("ClassA");
}
});
</script>
</body>
</html>