feat(js): hide mobile menu when click outside

- https://htmldom.dev/detect-clicks-outside-of-an-element
This commit is contained in:
MDLeom 2020-04-04 06:53:32 +01:00
parent 2a9756acd8
commit 17c1ad06a0
No known key found for this signature in database
GPG Key ID: 5D9DB57A25D34EE3
3 changed files with 25 additions and 9 deletions

View File

@ -1,6 +1,6 @@
<header id="header" class="header">
<%/* Nav menu for desktop */%>
<nav id="main-nav" class="main-nav">
<nav class="main-nav">
<% for (const i in theme.menu) { %>
<a class="main-nav-link" href="<%- url_for(theme.menu[i]) %>"><%= i %></a>
<% } %>
@ -26,9 +26,9 @@
<nav class="mobile-nav">
<h1 class="site-title"><a href="<%- url_for(theme.menu['Home']) %>"><%= config.title %></a></h1>
<ul class="mobile-nav-menu">
<label for="mobile-menu-toggle"><a class="menu-button no-underline">&#9776;</a></label>
<label for="mobile-menu-toggle"><a class="no-underline" id="menu-button">&#9776;</a></label>
<input id="mobile-menu-toggle" type="checkbox"/>
<ul class="mobile-nav-link">
<ul id="mobile-nav-link">
<div class="search-container">
<form id="searchFormMob" method="post" action="https://duckduckgo.com/" target="_blank" rel="noopener external nofollow noreferrer">
<input type="text" name="q" class="search-box" placeholder="Search..." title="Powered by DuckDuckGo">

View File

@ -618,7 +618,7 @@ td {
/* when it's not mobile */
.mobile-nav,
#mobile-menu-toggle,
.mobile-nav-link {
#mobile-nav-link {
display: none;
}
@ -628,7 +628,7 @@ td {
}
/* overlap other elements */
.mobile-nav-link {
#mobile-nav-link {
background: var(--main-bg-color);
color: var(--main-font-color);
border: 2px solid #999;
@ -643,7 +643,7 @@ td {
text-align: center;
}
.menu-button {
#menu-button {
font-size: 2em;
}
@ -764,7 +764,7 @@ svg#share:hover {
/* display links when menu button is clicked */
/* use grid to display each link in new line */
#mobile-menu-toggle:checked + .mobile-nav-link {
#mobile-menu-toggle:checked + #mobile-nav-link {
display: grid;
}
}

View File

@ -7,6 +7,22 @@ document.getElementById('search-click-mobile').addEventListener('click', () => {
searchFormMob.submit()
}, false)
// Hide mobile menu when click outside of the menu
document.addEventListener('click', (evt) => {
const mainNavDisplay = window.getComputedStyle(document.getElementsByClassName('main-nav')[0]).getPropertyValue('display')
const mobileNav = document.getElementById('mobile-nav-link')
const mobileToggle = document.getElementById('mobile-menu-toggle')
const isClickedOutside = !mobileNav.contains(evt.target)
// Exit if not in mobile view or menu button is clicked
// Menu button click triggers `menu-button` and `mobile-menu-toggle`
if (mainNavDisplay !== 'none' || evt.target.id === 'menu-button' || evt.target.id === 'mobile-menu-toggle') return
if (isClickedOutside) {
mobileToggle.checked = false
}
}, false)
// Web Share API
// https://developer.mozilla.org/en-US/docs/Web/API/Navigator/share
// Only available on supporting browsers and HTTPS