-
Notifications
You must be signed in to change notification settings - Fork 355
/
checkbox.js
65 lines (53 loc) · 1.43 KB
/
checkbox.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
65
/*
* This content is licensed according to the W3C Software License at
* https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document
*
* File: Checkbox.js
*
* Desc: Checkbox widget that implements ARIA Authoring Practices
*/
'use strict';
class Checkbox {
constructor(domNode) {
this.domNode = domNode;
this.domNode.tabIndex = 0;
if (!this.domNode.getAttribute('aria-checked')) {
this.domNode.setAttribute('aria-checked', 'false');
}
this.domNode.addEventListener('keydown', this.onKeydown.bind(this));
this.domNode.addEventListener('click', this.onClick.bind(this));
}
toggleCheckbox() {
if (this.domNode.getAttribute('aria-checked') === 'true') {
this.domNode.setAttribute('aria-checked', 'false');
} else {
this.domNode.setAttribute('aria-checked', 'true');
}
}
/* EVENT HANDLERS */
onKeydown(event) {
var flag = false;
switch (event.key) {
case ' ':
this.toggleCheckbox();
flag = true;
break;
default:
break;
}
if (flag) {
event.stopPropagation();
event.preventDefault();
}
}
onClick() {
this.toggleCheckbox();
}
}
// Initialize checkboxes on the page
window.addEventListener('load', function () {
let checkboxes = document.querySelectorAll('.checkboxes [role="checkbox"]');
for (let i = 0; i < checkboxes.length; i++) {
new Checkbox(checkboxes[i]);
}
});