Skip to content
This repository has been archived by the owner on Sep 11, 2019. It is now read-only.

Commit

Permalink
hide the usermenu on outside click
Browse files Browse the repository at this point in the history
Modifies the behavior of the header usermenu to hide not only on click of its trigger link, but also on click of anywhere outside of its descendents.
  • Loading branch information
James Seppi committed Apr 19, 2018
1 parent 8052679 commit 347fa7f
Showing 1 changed file with 41 additions and 3 deletions.
44 changes: 41 additions & 3 deletions frontend/source/js/common/usermenu.js
@@ -1,9 +1,29 @@
// @ts-check
/* global document */

/**
* Determines if `targetEl` is a descendant of the given `parentEl`.
*
* @param { HTMLElement|Element } parentEl the parent element
* @param { HTMLElement|EventTarget|Element|null } targetEl the element in question
* @returns { Boolean } `true` if `targetEl` is a descendant of `parentEl`.
*/
function isDescendantOf(parentEl, targetEl) {
if (!targetEl || parentEl === targetEl) { return true; }

let result = false;
for (let index = 0; index < parentEl.children.length; index++) {
const element = parentEl.children[index];
result = result || isDescendantOf(element, targetEl);
}

return result;
}

function enableUsermenu() {
const menu = document.querySelector('#usermenu');
const trigger = document.querySelector('#usermenu .usermenu-trigger');
const body = document.body;
const openLabel = 'Show user menu';
const closeLabel = 'Close user menu';

Expand All @@ -15,12 +35,30 @@ function enableUsermenu() {
trigger.setAttribute('aria-expanded', false.toString());
trigger.setAttribute('aria-label', openLabel);

trigger.addEventListener('click', (e) => {
menu.classList.toggle('is-open');
const isOpen = menu.classList.contains('is-open');
/**
* @param {Boolean} isOpen
*/
const toggleMenu = (isOpen) => {
if (isOpen) {
menu.classList.add('is-open');
} else {
menu.classList.remove('is-open');
}

trigger.setAttribute('aria-expanded', isOpen.toString());
trigger.setAttribute('aria-label', isOpen ? closeLabel : openLabel);
};

trigger.addEventListener('click', (e) => {
e.preventDefault();
const isOpen = menu.classList.contains('is-open');
toggleMenu(!isOpen);
});

body.addEventListener('click', (e) => {
if (!isDescendantOf(menu, e.target)) {
toggleMenu(false);
}
});
}

Expand Down

0 comments on commit 347fa7f

Please sign in to comment.