UNPKG

1.63 kBJavaScriptView Raw
1
2export const Alert = {
3
4 className: 'alert',
5 classFade: 'fade',
6 classFadeIn: 'active',
7 classCloseBtn: 'close',
8 animationDuration: 150,
9
10 init(alert) {
11 this.addEvents(alert);
12 },
13
14 initAll(node = document) {
15 const alerts = node.getElementsByClassName(this.className);
16 [].forEach.call(alerts, alert => {
17 this.init(alert);
18 })
19 },
20
21 addEvents(alert) {
22 const btn = this.getCloseBtn(alert);
23 if (btn) {
24 btn.addEventListener('click', () => {
25 this.close(alert);
26 })
27 }
28 },
29
30 getCloseBtn(alert) {
31 return alert.getElementsByClassName(this.classCloseBtn)[0] || false;
32 },
33
34 hasAnimation(alert) {
35 return alert.classList.contains(this.classFade);
36 },
37
38 show(alert) {
39 return new Promise(resolve => {
40 alert.classList.add(this.classFadeIn);
41 setTimeout(resolve, this.animationDuration);
42 });
43 },
44
45 hide(alert) {
46 return new Promise(resolve => {
47 alert.classList.remove(this.classFadeIn);
48 setTimeout(resolve, this.animationDuration);
49 });
50 },
51
52 remove(alert) {
53 alert.parentNode.removeChild(alert);
54 },
55
56 close(alert) {
57 if (this.hasAnimation(alert)) {
58 this.hide(alert).then(() => {
59 this.remove(alert);
60 })
61 } else {
62 this.remove(alert);
63 }
64 }
65
66};
67
68document.addEventListener('DOMContentLoaded', () => {
69 Alert.initAll();
70});