Jake Vanderwerf
2026-01-01 c06013234d16ab3889bd7fce09f6606b45fd2b9f
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
class Popup {
    constructor(config = {}) {
        this.config = {
            toggle: document.querySelector('[data-toggles]'),
            popup: document.querySelector('.jvb-pop'),
            name: 'Popup',
            onOpen: () =>{},
            onClose: () =>{},
            onEscape: () =>{},
            ... config
        };
 
        this.a11y = window.jvbA11y;
        this.toggleID = this.config.toggle.id === '' ? '.'+this.config.toggle.className.split(' ').join('.') : this.config.toggle.id;
 
        this.initListeners();
    }
 
    initListeners()
    {
        this.clickHandler = this.handleClick.bind(this);
        this.keyHandler = this.handleEscape.bind(this);
 
        document.addEventListener('click', this.handleToggle.bind(this));
    }
 
    handleToggle(e) {
        if (e.target === this.config.toggle || e.target.closest(this.toggleID)){
            this.togglePopup();
        }
    }
    handleClick(e) {
        if (!this.config.popup.contains(e.target)
            && e.target !== this.config.toggle) {
            this.closePopup();
        } else if (window.targetCheck(e, '.close')) {
            this.closePopup();
        }
    }
 
    togglePopup() {
        if (!this.config.popup.classList.contains('expanded')) {
            this.openPopup();
        } else {
            this.closePopup();
        }
    }
    openPopup(message = `Opened ${this.config.name}`) {
        this.config.popup.classList.add('expanded');
        this.config.toggle.classList.add('expanded');
        this.config.toggle.title = `Hide ${this.config.name}`;
        this.config.toggle.ariaExpanded = true;
        this.config.toggle.querySelector('span').textContent = `Close ${this.config.name}`;
        this.a11y.announce(message);
        this.config.onOpen();
        document.addEventListener('keydown', this.keyHandler);
        document.addEventListener('click', this.clickHandler);
    }
    closePopup(message = `Closed ${this.config.name}`) {
        this.config.popup.classList.remove('expanded');
        this.config.toggle.classList.remove('expanded');
        this.config.toggle.title = `Show ${this.config.name}`;
        this.config.toggle.ariaExpanded = false;
 
        this.config.toggle.querySelector('span').textContent = '';
        this.a11y.announce(message);
        this.config.onClose();
        document.removeEventListener('keydown', this.keyHandler);
        document.removeEventListener('click', this.clickHandler);
    }
    handleEscape(e) {
        if (e.key === 'Escape') {
            this.closePopup(`Closed ${this.config.name} with escape key`);
            this.config.onEscape();
        }
    }
}
 
window.jvbPopup = Popup;