Reputation: 453
I have a menu that opens when the user clicks the icon. I want the menu to close when the user clicks anywhere else on the page, but I'm having trouble finishing the function. Below is my html and functions:
<div id="header">
<div id="menu">
<div class="menu-container" id="myLinks">
<?php wp_nav_menu(array('container_class' => 'hike-menu', 'theme_location' => 'home-top')); ?>
<?php wp_nav_menu(array('container_class' => 'hike-menu', 'theme_location' => 'hike')); ?>
<?php wp_nav_menu(array('container_class' => 'primary-menu', 'theme_location' => 'primary')); ?>
</div>
<a href="javascript:void(0);" class="icon" onclick="myToggleFunction()" id="toggle-menu">
<span></span>
</a>
</div>
</div>
function myToggleFunction() {
var element = document.getElementById("toggle-menu");
element.classList.add("active");
var x = document.getElementById("myLinks");
if (x.style.width === "290px") {
x.style.width = "0px";
element.classList.remove("active");
} else {
x.style.width = "290px";
}
}
jQuery(document.body).click(function(e) {
if (jQuery("#toggle-menu").hasClass("active") && jQuery("#myLinks").css("width", "290px")) {
jQuery("#myLinks").css("width", "0px");
jQuery("#toggle-menu").removeClass("active");
}
});
When the user clicks on "toggle-menu", the menu opens. The myToggleFunction() works great, but it's getting the menu to close when I click anywhere outside of it that's the problem. Does anyone know how I can rework my function to achieve this?
Upvotes: 0
Views: 2520
Reputation: 16184
Check the event.target
to determine whether the menu should be closed or not.
$(function() {
$("html").on("click", function(e) {
let $t = $(e.target),
$myLinks = $("#myLinks"),
$toggleMenu = $("#toggle-menu");
if ($t.is($myLinks) || $myLinks.has($t).length) {
//clicked in the menu. do nothing
} else if ($t.is($toggleMenu) || $toggleMenu.has($t).length) {
$myLinks.toggleClass("open");
} else {
$myLinks.removeClass("open");
}
})
});
html,
body {
margin: 0;
min-height: 100%;
background: #eee;
}
#myLinks {
background: #ccc;
max-height: 0px;
height:auto;
overflow: hidden;
transition: max-height 0.4s;
}
#myLinks.open {
max-height: 200px;
}
#myLinks a {
display: block;
margin: 10px;
}
#toggle-menu {
background: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="header">
<div id="menu">
<div class="menu-container" id="myLinks">
<a href="#">menu</a>
<a href="#">items</a>
<a href="#">here</a>
</div>
<a href="#" class="icon" id="toggle-menu">
<span>toggle menu</span>
</a>
</div>
</div>
Upvotes: 1
Reputation: 21
you can set the your close menu function on body and set e.stopPropagation() on menu itself
Upvotes: 0