forked from vasanthk/js-bits
-
Notifications
You must be signed in to change notification settings - Fork 0
/
event-delegation.js
66 lines (57 loc) · 1.46 KB
/
event-delegation.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
59
60
61
62
63
64
/**
* Event Delegation in Vanilla JS
*
* JSFiddle:
* https://jsfiddle.net/vasanthkay/sokgevhr/7/
*
* @Reference:
* Excellent Article:
* http://codepen.io/32bitkid/post/understanding-delegated-javascript-events
*/
//HTML CODE
//
//<ul class="toolbar">
// <li>
// <button class="btn"><i class="fa fa-pencil"></i> Pencil</button>
// </li>
// <li>
// <button class="btn"><i class="fa fa-paint-brush"></i> Pen</button>
// </li>
// <li class="separator"></li>
// <li>
// <button class="btn"><i class="fa fa-eraser"></i> Eraser</button>
// </li>
//</ul>
// HELPER FUNCTION
function delegate(criteria, listener) {
return function (e) {
var el = e.target;
do {
if (!criteria(el)) {
continue;
}
e.delegateTarget = el;
listener.call(this, e);
return;
} while ((el = el.parentNode));
};
}
// Example of Event Delegation
// Custom filter to check for required DOM elements
var buttonsFilter = function (elem) {
return (elem instanceof HTMLElement) && elem.matches(".btn");
// OR
// For < IE9
// return elem.classList && elem.classList.contains('btn');
};
var buttonHandler = function (e) {
var button = e.delegateTarget;
var hasActiveClass = button.classList.contains('active');
if (!hasActiveClass(button)) {
button.classList.add('active');
} else {
button.classList.remove('active');
}
};
// Add the event listener
document.addEventListener("click", delegate(buttonsFilter, buttonHandler));