]> BookStack Code Mirror - bookstack/blob - resources/assets/js/components/dropdown.js
Merge pull request #1072 from CliffyPrime/german_update
[bookstack] / resources / assets / js / components / dropdown.js
1 /**
2  * Dropdown
3  * Provides some simple logic to create simple dropdown menus.
4  */
5 class DropDown {
6
7     constructor(elem) {
8         this.container = elem;
9         this.menu = elem.querySelector('ul');
10         this.toggle = elem.querySelector('[dropdown-toggle]');
11         this.setupListeners();
12     }
13
14     show() {
15         this.menu.style.display = 'block';
16         this.menu.classList.add('anim', 'menuIn');
17         this.container.addEventListener('mouseleave', this.hide.bind(this));
18
19         // Focus on first input if existing
20         let input = this.menu.querySelector('input');
21         if (input !== null) input.focus();
22     }
23
24     hide() {
25         this.menu.style.display = 'none';
26         this.menu.classList.remove('anim', 'menuIn');
27     }
28
29     setupListeners() {
30         // Hide menu on option click
31         this.container.addEventListener('click', event => {
32              let possibleChildren = Array.from(this.menu.querySelectorAll('a'));
33              if (possibleChildren.indexOf(event.target) !== -1) this.hide();
34         });
35         // Show dropdown on toggle click
36         this.toggle.addEventListener('click', this.show.bind(this));
37         // Hide menu on enter press
38         this.container.addEventListener('keypress', event => {
39                 if (event.keyCode !== 13) return true;
40                 event.preventDefault();
41                 this.hide();
42                 return false;
43         });
44     }
45
46 }
47
48 export default DropDown;