-
Notifications
You must be signed in to change notification settings - Fork 0
/
event_listeners.js
58 lines (46 loc) · 1.32 KB
/
event_listeners.js
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
/* Can be combined
const grandparent = document.querySelector('.grandparent');
const parent = document.querySelector('.parent');
const child = document.querySelector('.child');
grandparent.addEventListener('click', (e) => {
console.log("Grandparent");
}, {capture: true});
parent.addEventListener('click', (e) => {
e.stopPropagation();
console.log("Parent");
});
child.addEventListener('click', (e) => {
console.log("Child");
setTimeout(() => {
parent.removeEventListener("click", printHi)
}, 2000);
});
document.addEventListener('click', (e) => {
console.log("Document");
});
function printHi() {
console.log("Hi");
}
*/
const divs = document.querySelectorAll('div');
/* Does not work fpr divs added after
divs.forEach(div => {
div.addEventListener('click', () => {
console.log("hi");
});
});
*/
addGlobalEventListener('click', 'div', e => {
console.log("hi");
});
function addGlobalEventListener(type, selector, callback) {
document.addEventListener(type, e => {
if(e.target.matches(selector))
callback(e);
});
}
const newDiv = document.createElement('div');
newDiv.style.height = "200px";
newDiv.style.width = "200px";
newDiv.style.backgroundColor = "purple";
document.body.append(newDiv);