Bootstrap-4 navbar collapse menu close when clicking outside the navbar in mobile

Hey Digitfeast readers, Today I will write the code for the Bootstrap-4 navbar collapse menu close when clicking outside of the navigation bar on mobile. I write HTML here for the navigation bar and javascript for the close collapsing menu when we click outside the navbar into mobile. I used bootstrap-4 library and jquery. To see the result click outside of the navbar.

bootstrap 4 collapse close on click outside

Here is the code - <!DOCTYPE html> <html lang="en"> <head> <title></title> <meta charset="utf-8"> <meta name="keyword" content=""> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href=""> </head> <body> <header> <nav class="navbar navbar-expand-md bg-dark navbar-dark"> <!-- Site Logo Here --> <a class="navbar-brand" href="#">Logo</a> <!-- Collapsibe Button --> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#mobilemenu"> <span class="navbar-toggler-icon"></span> </button> <!-- Header links --> <div class="collapse navbar-collapse" id="mobilemenu"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">About</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Services</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Event</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Contact</a> </li> </ul> </div> </nav> </header> <body>
Something here... </body> <footer>Something here...</footer>
<script src=""></script> <script src=""></script> <script src=""></script>
<!-- Script For Closing Menu from Outside -->
<script> $(document).ready(function () { $(document).click(function (event) { var click = $(; var _open = $(".navbar-collapse").hasClass("show"); if (_open === true && !click.hasClass("navbar-toggler")) { $(".navbar-toggler").click(); } }); }); </script> </body> </html>

Output -
Close bootstrap collapse when clicking anywhere in the body

Post a Comment