Default Image

Months format

Show More Text

Load More

Related Posts Widget

Article Navigation

Contact Us Form

404

Sorry, the page you were looking for in this blog does not exist. Back Home

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>Digitfeast.com</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="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> </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="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<!-- Script For Closing Menu from Outside -->
<script>     $(document).ready(function () {      $(document).click(function (event) {      var click = $(event.target);     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


No comments:

Post a Comment