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;