PluginProbe
Polylang / trunk
Polylang vtrunk
3.8.9 3.8.8 3.8.7 3.8.6 3.8.5 3.8.4 3.8.3 2.7 2.7.0.1 2.7.1 2.7.2 2.7.3 2.7.4 2.8 2.8.1 2.8.2 2.8.3 2.8.4 2.9 2.9.1 2.9.2 3.0 3.0.1 3.0.2 3.0.3 All 233 releases
polylang / js / build / frontend-dropdown.js

frontend-dropdown.js in Polylang trunk, at js/build/frontend-dropdown.js

100 lines 2.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 /******/ "use strict";
2 /* unused harmony export default */
3 /**
4 * Allows to open/close the language switcher's submenus when the "dropdown" layout is used.
5 */
6
7 class Dropdown {
8 /**
9 * Attaches events to the dropdown's elements.
10 *
11 * @param {HTMLElement} button The button that opens/closes the dropdown.
12 */
13 constructor( button ) {
14 this.button = button;
15 this.closeOnClickOutsideBinded = this.closeOnClickOutside.bind( this );
16
17 button.setAttribute( 'aria-expanded', 'false' );
18
19 button.parentNode.addEventListener(
20 'mouseenter',
21 this.open.bind( this )
22 );
23 button.parentNode.addEventListener(
24 'mouseleave',
25 this.close.bind( this )
26 );
27 button.addEventListener( 'click', this.toggle.bind( this ) );
28 button.nextElementSibling.addEventListener(
29 'keydown',
30 this.closeOnListKeydown.bind( this )
31 );
32 button.nextElementSibling
33 .querySelector( 'li:last-child > a' )
34 .addEventListener( 'blur', this.closeOnLastLinkBlur.bind( this ) );
35 }
36
37 /**
38 * Opens the submenu.
39 */
40 open() {
41 this.button.setAttribute( 'aria-expanded', 'true' );
42 document.addEventListener( 'click', this.closeOnClickOutsideBinded );
43 }
44
45 /**
46 * Closes the submenu.
47 */
48 close() {
49 this.button.setAttribute( 'aria-expanded', 'false' );
50 document.removeEventListener( 'click', this.closeOnClickOutsideBinded );
51 }
52
53 /**
54 * Toggles the submenu.
55 */
56 toggle() {
57 const expanded = this.button.getAttribute( 'aria-expanded' );
58 if ( 'true' === expanded ) {
59 this.close();
60 } else {
61 this.open();
62 }
63 }
64
65 /**
66 * Event callback that closes the submenu when pressing the Escape key while in the list.
67 *
68 * @param {Event} event The event.
69 */
70 closeOnListKeydown( event ) {
71 if ( event.key === 'Escape' ) {
72 this.button.focus();
73 this.close();
74 }
75 }
76
77 /**
78 * Event callback that closes the submenu when the last link in the list looses focus (to a target outside the list).
79 *
80 * @param {Event} event The event.
81 */
82 closeOnLastLinkBlur( event ) {
83 if ( ! this.button.parentNode.contains( event.relatedTarget ) ) {
84 this.close();
85 }
86 }
87
88 /**
89 * Event callback that closes the submenu when the user clicks outside the dropdown.
90 *
91 * @param {Event} event The event.
92 */
93 closeOnClickOutside( event ) {
94 if ( ! this.button.parentNode.contains( event.target ) ) {
95 this.close();
96 }
97 }
98 }
99
100