Hide an expanded menu when clicking outside of the container: how to use code snipet
By using jQuery, you can bind to the document click event and hides the div container when the clicked element isn’t the container itself or descendant of the div element.
var container = $("#sub-menu");
if (!container.is(event.target) && !container.has(event.target).length) {
container.hide();
}
If you want to hide that container without being tested the container itself or descendant of the div element just remove the condition and simply use container.hide();
.
Also, rather than setting display: none;
on sub-menu
in the CSS, set it manually so that you can toggle the sub-menu
from the very first click.
Have a look at the snippet below:
var x = document.getElementById("sub-menu");
x.style.display = "none";
$(document).click(function (evt) {
if ($(evt.target).is('#main-menu')) { // control click event if it's main-menu
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
else {
var container = $("#sub-menu");
if (!container.is(event.target) && !container.has(event.target).length) { // if you don't want that remove the condition and write container.hide(); only
container.hide();
}
}
});
#main-menu {
display: inline-block;
height: 20px;
width: 100px;
background: blue;
padding: 5%;
}
#sub-menu {
display: inline-block;
height: 50px;
width: 50px;
background: red;
}
<script src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<div id="main-menu">Main menu</div>
<div id="sub-menu" class="sub-menu-class">Sub menu</div>
Want to hide menu by clicking outside the menu element
var $menu = $('.main-nav');
$('mobile_nav').click(function () {
$menu.toggle();
});
$(document).mouseup(function (e) {
if (!$menu.is(e.target) // if the target of the click isn't the container...
&& $menu.has(e.target).length === 0) // ... nor a descendant of the container
{
desktop_nav.slideUp("slow", "easeOutExpo").removeClass("js-opened");
$(this).removeClass("active");
}
});
Hide menu, when clicking anywhere else than the menu
Use css attribute left
to detect if the menu is visible instead of :visibe
because it's bot work with chrome, see jquery .is(“:visible”) not working in Chrome.
You have just to detect if the menu is visible (use the css attribute left) because if the menu css left=0px
that mean it's visible, and after that if the click
is outside of menu or not and so if outside close it.
Take a look at Your updating fiddle work fine just by adding the following handle
that detect outside click :
JS :
$(document).click(function(e) {
//if the menu is visible
if($(".menu").css('left') =="0px"){
//if the click is outside of menu
if($(e.target).closest('.menu').length == 0){
$('.closed').click();
}
}
});
jQuery - Hide a div menu after clicking outside div
add this snippet in your code
$(document).click(function(e){
var myTarget = $(".subnav");
var clicked = e.target.className;
if($.trim(myTarget) != '') {
if($("." + myTarget) != clicked) {
$("ul.subnav").slideUp('slow').hide();
}
}
});
this will close your ul.subnav
when you click anywhere in your document.
I cannot hide navigation dropdown when click outside
You can remove class 'active' on outside click:
window.addEventListener('click', function(e) {
var els = document.getElementsByClassName('dropdown');
for (var i = 0; i < els.length; i++) {
if (els[i].contains(e.target)) {
// Clicked on dropdown
} else {
// Clicked outside the dropdown
els[i].classList.remove('active');
}
}
});
// Navigation mobilevar getNavbar = document.querySelector('nav');var getNavbarToggler = document.querySelector('.navbar-toggler');var getNavbarNav = document.querySelector('.navbar-nav');
getNavbarToggler.addEventListener('click', toggleNavbar);
function toggleNavbar() { getNavbarToggler.classList.toggle('active'); getNavbarNav.classList.toggle('active');}
// Dropdown Menu
var getNavItem = document.querySelectorAll('.nav-item');getNavItem.forEach(item => { item.addEventListener('click', function(e) { var siblings = getSiblings(this); siblings.forEach(item => { item.classList.remove('active'); }) this.classList.toggle('active');
});
});
// Get Siblingsvar getSiblings = function(elem) { var siblings = []; var sibling = elem.parentNode.firstChild; for (; sibling; sibling = sibling.nextSibling) { if (sibling.nodeType !== 1 || sibling === elem) continue; siblings.push(sibling); } return siblings;};var elem = document.querySelector('#some-element');
// code for hiding dropdown
window.addEventListener('click', function(e) {
var els = document.getElementsByClassName('dropdown');
for (var i = 0; i < els.length; i++) { if (els[i].contains(e.target)) { // Clicked on dropdown } else { // Clicked outside the dropdown els[i].classList.remove('active'); } }});
/* Global Styles */
* { margin: 0; padding: 0; box-sizing: border-box;}
body { overflow-x: hidden;}
ul { list-style: none;}
a { text-decoration: none;}
.container { max-width: 1170px; margin: 0 auto;}
/* Navigation */
nav { background: #333; transition: all ease .4s;}
.navbar { display: flex; justify-content: space-between; align-items: center; padding: 0 10px; position: relative;}
.navbar-brand { display: block; color: #fff; font-size: 30px;}
.navbar-nav { display: flex; justify-content: space-between; align-items: center;}
.nav-link,.dropdown-item { display: block; color: #fff; padding: 20px 16px; text-align: center; cursor: pointer;}
.nav-link:hover,.dropdown-item:hover { background: #111;}
.nav-link.active,.nav-link.active:hover { background-color: #4CAF50;}
.dropdown-menu { display: none;}
.nav-item.active .dropdown-menu { display: block;}
.nav-link i { transition: all ease .4s;}
.nav-item.active i { transform: rotate(180deg);}
.dropdown { position: relative;}
.dropdown-menu { position: absolute; background: #333; left: 0; width: 100%; text-align: center;}
.arrow-icon { width: 0; height: 0; border-style: solid; border-width: 6px 6px 0 6px; border-color: #fff transparent transparent transparent; position: absolute;}
.navbar-toggler { display: none; cursor: pointer; position: relative; width: 30px; height: 30px;}
.navbar-toggler .navbar-toggler-icon { width: 100%; height: 3px; margin: 5px 0; background: #fff; display: block; transition: all ease .3s;}
.sticky-nav { position: fixed; top: 0; width: 100%; transition: all ease .4s;}
@media (max-width: 700px) { nav { position: fixed; top: 0; left: 0; width: 100%; } .dropdown-menu { position: relative; background: #444; } .dropdown-item { text-align: left; padding-left: 50px; } .navbar-brand { padding: 10px 0; } .navbar-toggler { display: block; transition: all ease .3s; } .navbar-toggler.active { transform: rotate(225deg); } .navbar-toggler.active .navbar-toggler-icon { position: absolute; top: 30%; transition: all ease .3s; } .navbar-toggler.active .navbar-toggler-icon:first-child { transform: rotate(-3deg); } .navbar-toggler.active .navbar-toggler-icon:nth-child(2) { opacity: 0; } .navbar-toggler.active .navbar-toggler-icon:last-child { transform: rotate(90deg); } .navbar-nav { position: absolute; top: 100%; left: 0; width: 100%; height: 0; display: block; overflow: hidden; background: #333; transition: all ease .4s; } .navbar-nav.active { height: 100vh; overflow: auto; } .nav-link { text-align: left; }}
<nav> <div class="container navbar"> <a href="#" class="navbar-brand">Navigation</a> <div class="navbar-toggler"> <span class="navbar-toggler-icon"></span> <span class="navbar-toggler-icon"></span> <span class="navbar-toggler-icon"></span> </div> <ul class="navbar-nav"> <li class="nav-item"> <a href="#" class="nav-link active">Home</a> </li> <li class="nav-item dropdown" id="m1"> <a class="nav-link">Dropdown 1 <i class="fa fa-caret-down"></i> </a> <div class="dropdown-menu"> <a href="#" class="dropdown-item">Item 1</a> <a href="#" class="dropdown-item">Item 2</a> <a href="#" class="dropdown-item">Item 3</a> </div> </li> <li class="nav-item"> <a href="#" class="nav-link">About</a> </li> <li class="nav-item dropdown"> <a class="nav-link">Dropdown 2 <i class="fa fa-caret-down"></i> </a> <div class="dropdown-menu"> <a href="#" class="dropdown-item">Item 1</a> <a href="#" class="dropdown-item">Item 2</a> <a href="#" class="dropdown-item">Item 3</a> </div> </li> <li class="nav-item"> <a href="#" class="nav-link">Contact</a> </li> </ul> </div></nav>
Related Topics
Why Is React Webpack Production Build Showing Blank Page
Starting the Week on Monday With Isoweekday()
Passing Value from Java to JavaScript
How to Compare Two Objects and Get Key-Value Pairs of Their Differences
Can We Have Code After Location.Reload(True)
Onchange Is Not Triggering in React Js
How to Hide the Android Keyboard Using JavaScript
How to Move the Mouse Pointer and Click With Selenium Webdriver JavaScript
Best Way to Get Objects With Highest Property Value
Is There a Way That I Can Check If a Data Attribute Exists
Vue.Js Refs Are Undefined, Even Though This.$Refs Shows Theyre There
Blob Createobjecturl Download Not Working in Firefox (But Works When Debugging)
Why Is It a Bad Practice to Return Generated HTML Instead of Json or Is It
How to Get the Latest and Oldest Record in Mongoose.Js (Or Just the Timespan Between Them)
Trying to Load a Script File from My Node Server - Get 404
Google Firestore - How to Get Several Documents by Multiple Ids in One Round-Trip
Nested Json: How to Add (Push) New Items to an Object
Callback Function Cannot Access Variable Within Parent Function'S Scope