-
Notifications
You must be signed in to change notification settings - Fork 3
/
Modal.js
69 lines (58 loc) · 1.53 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
// Modal base class
export class Modal {
constructor(options) {
this.domId = options.domId;
this.templateId = options.templateId;
this.modal = this.createDialogElement();
this.titleElement = this.modal.querySelector('.modal-title');
this.closeButton = this.modal.querySelector('.button-close');
this.closeButton.onclick = () => this.hide();
this._bindEventListeners();
this.setTitle(options.title);
}
setTitle(title) {
this.titleElement.textContent = title;
}
_bindEventListeners() {
this.modal.addEventListener('click', (event) => {
if (event.target == this.modal) {
this.hide();
}
});
window.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
this.hide();
}
});
}
createDialogElement() {
const template = document.getElementById(this.templateId);
if (!template) {
console.error(`Template with ID ${this.templateId} not found.`);
return;
}
const clone = template.content.cloneNode(true);
const modalElement = clone.firstElementChild;
modalElement.id = this.domId;
if (!modalElement) {
console.error(
`No modal element found in the template with ID ${this.templateId}.`,
);
return;
}
document.body.appendChild(modalElement);
return modalElement;
}
show() {
this.handleShow();
}
hide() {
this.handleHide();
}
handleShow() {
this.modal.classList.add('show');
}
handleHide() {
this.modal.classList.remove('show');
}
}