How can I close an open collapsed navbar on clicking outside of the navbar element? Currently, the only way to open or close it is by clicking on the navbar-toggle button.
See here for an example and code:
So far, I have tried the following which doesn't seem to work:
$(document).ready(function () {
$(document).click(function () {
// if($(".navbar-collapse").hasClass("in")){
$('.navbar-collapse').collapse('hide');
// }
});
});
But the above method is not working
the easiest way would be to attach a click eventlistener to the body tag.
document.body.addEventListener('click', (e) => {
if($(".navbar-collapse").hasClass("in")){
$('.navbar-collapse').collapse('hide');
}
})
You can define a function and call on mouseleave
. Here is an example:
function showMeTheMoney() { $('.treasure').toggle(); }
.treasure { background:blue; color:white width:100px;height:50px; position:absolute;bottom:0;right:0; display:none; } div { height:200px;width:200px; } .somespan { width:100px; height:100px; background:yellow; color:red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <span class="somespan" onmouseleave="showMeTheMoney();">Hover this red span and leave it with your mouse to reveal the treasure</span> <span class="treasure">The treasure is found.</span> </div>
You should add an event listener on the document and check if the click is outside the navbar:
// listen to clicks in document
document.addEventListener("click", (evt) => {
let targetElement = evt.target;
const navbar = document.querySelector('.navbar-collapse');
const navbarToggler = document.querySelector('.navbar-toggle');
do {
// open menu when click is on toggle button and menu does not have the 'in' class
if (targetElement == navbarToggler && ! navbar.classList.contains('in')) {
navbar.classList.add('in');
return;
}
// do nothing when clicked in navbar
else if (targetElement == navbar) {
return;
}
// Go up the DOM
targetElement = targetElement.parentNode;
} while (targetElement);
// when clicked outside of navbar
navbar.classList.remove('in');
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.