Completed
Push — master ( 530622...0684ff )
by D
02:37
created

Accordion.onInit   A

Complexity

Conditions 5

Size

Total Lines 4
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 4
c 0
b 0
f 0
rs 9.3333
cc 5
1
import {define} from "../globals/globals";
2
import {AccordionInterface} from "../interfaces/AccordionInterface";
3
import {AccordionOptions} from '../types/AccordionOptions'
4
5
(function (root, factory) {
6
    if (typeof define === 'function' && define.amd) {
7
        define([], factory);
8
    } else if (typeof module === 'object' && module.exports) {
9
        module.exports = factory();
10
    } else {
11
        root!.Accordion = factory();
12
    }
13
}(typeof self !== 'undefined' ? self : this, function () {
14
15
    class Accordion implements AccordionInterface {
16
        public options: AccordionOptions;
17
18
        constructor(options: AccordionOptions = {}) {
19
            this.options = options as object;
20
            this.options.el = typeof options.el === 'string' ? document.querySelectorAll(options.el) : options.el || document.querySelectorAll('.accordion');
21
            this.onInit();
22
        }
23
24
        protected onInit(): void {
25
            this.addClasses();
26
            this.toggleState();
27
        }
28
29
        static closeAll(accordions: NodeListOf<HTMLElement>): void {
30
            accordions.forEach(function (accordion: Element) {
31
                accordion.classList.remove('active')
32
            })
33
        }
34
35
        protected addClasses(): void {
36
            (this.options.el as NodeListOf<HTMLElement>).forEach(function (element: HTMLElement) {
37
                element.classList.add('accordion')
38
            })
39
        }
40
41
        protected toggleState(): void {
42
            let that = this;
43
44
            (that.options.el as NodeListOf<HTMLElement>).forEach(function (element: HTMLElement) {
45
                element.firstElementChild!.addEventListener('click', function () {
46
                    if(that.options.openOneCloseAll) {
47
                        Accordion.closeAll(that.options.el as NodeListOf<HTMLElement>);
48
                        (this as HTMLElement).parentElement!.classList.toggle('active')
49
                    }
50
                    else {
51
                        element.classList.toggle('active')
52
                    }
53
                })
54
            })
55
        }
56
    }
57
58
    return Accordion;
59
}));