function hideOnClickOutsided(element, btn) { // given a menu element and btn, hide the menu // whenever the click is not on either the element // or the btn the opened it const outsideClickListener = event => { if (!element.contains(event.target) && (event.target.id != btn)) { // or use: event.target.closest(selector) === null if (isVisible(element)) { element.classList.remove('active'); removeClickListener(); } } }; const removeClickListener = () => { document.removeEventListener('click', outsideClickListener); }; document.addEventListener('click', outsideClickListener); } const isVisible = elem => !!elem && !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); // source (2018-03-11): https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js //---------------------------------------- //Initialize main menu bar with progressive enhancements //if we find the menu items //---------------------------------------------- // Account Menu if (document.getElementById('account-menu')) { var account_a = document.getElementById('account-menu'); var account_div = document.getElementById('user-menu'); //Add button function account_a.addEventListener('click', function(e){ e.preventDefault(); account_div.classList.toggle('active'); account_div.focus(); hideOnClickOutsided(account_div, account_a.id); }, false); // Notebooks Menu var notebook_a = document.getElementById('notebook-menu-link'); var notebook_div = document.getElementById('notebooks-menu'); //Add button function notebook_a.addEventListener('click', function(e){ e.preventDefault(); notebook_div.classList.toggle('active'); notebook_div.focus(); hideOnClickOutsided(notebook_div, notebook_a.id); }, false); } if (typeof(document.getElementById('js-overlay-login')) != 'undefined' && document.getElementById('js-overlay-login') != null) { // Select your overlay trigger var trigger = document.getElementById('overlay-trigger'); addLoginHandler(trigger); function addLoginHandler(el){ console.log(el); el.addEventListener('click', function(e){ e.preventDefault(); var modal = modalBox(el, document.getElementById('js-overlay-login')); }); } }