This repository has been archived by the owner on Apr 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
modal.js
93 lines (79 loc) · 2.48 KB
/
modal.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
class Dialog {
constructor(dialogElement, overlayElement) {
this.dialogElement = dialogElement;
this.overlayElement = overlayElement;
//this.focusedElBeforeOpen = document.activeElement;
this.focusableEls = Array.prototype.slice.call(this.dialogElement.querySelectorAll('a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), [tabindex="0"]'));
this.firstFocusableEl = this.focusableEls[0];
this.lastFocusableEl = this.focusableEls[ this.focusableEls.length - 1 ];
//this.close();
}
open() {
const Dialog = this;
this.dialogElement.removeAttribute('aria-hidden');
this.overlayElement.removeAttribute('aria-hidden');
this.focusedElBeforeOpen = document.activeElement;
this.dialogElement.addEventListener('keydown', function(e) {
Dialog._handleKeyDown(e);
});
this.overlayElement.addEventListener('click', function() {
Dialog.close();
});
this.firstFocusableEl.focus();
}
close(){
this.dialogElement.setAttribute('aria-hidden', true);
this.overlayElement.setAttribute('aria-hidden', true);
console.log(this.focusedElBeforeOpen);
if ( this.focusedElBeforeOpen ) {
this.focusedElBeforeOpen.focus();
}
}
_handleKeyDown(e){
const Dialog = this;
const KEY_TAB = 9;
const KEY_ESC = 27;
function handleBackwardTab() {
if ( document.activeElement === Dialog.firstFocusableEl ) {
e.preventDefault();
Dialog.lastFocusableEl.focus();
}
}
function handleForwardTab() {
if ( document.activeElement === Dialog.lastFocusableEl ) {
e.preventDefault();
Dialog.firstFocusableEl.focus();
}
}
switch(e.keyCode) {
case KEY_TAB:
if ( Dialog.focusableEls.length === 1 ) {
e.preventDefault();
break;
}
if ( e.shiftKey ) {
handleBackwardTab();
} else {
handleForwardTab();
}
break;
case KEY_ESC:
Dialog.close();
break;
default:
break;
}
}
addEventListeners(openDialogSel, closeDialogSel){
const Dialog = this;
openDialogSel.addEventListener('click', function() {
Dialog.open();
});
const closeDialogElements = document.querySelectorAll(closeDialogSel);
for (let closeDialogElement of closeDialogElements) {
closeDialogElement.addEventListener('click', function() {
Dialog.close();
});
}
}
}