How to collapse the navbar in mobile view on click of document

Manideepgoud
Posted by Manideepgoud under jQuery category on | Points: 40 | Views : 2420
Hi,
In the below code am trying to make navbar close while onclick on the document(body).
<!DOCTYPE html>
<html lang="en">
<head>
<title>Navbar</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
$(document).on('click',function(event){
var clickover = $(event.target);
var _opened = $(".collapse").hasClass("collapse in");
if (_opened === true && !clickover.hasClass("navbar-toggle") && !$(event.target).closest(".submenu").length) {
$("button.navbar-toggle").click();
}
});
});
</script>
</head>
<body>

<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">MySiteName</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">About us<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#">Case Studies</a></li>
<li><a href="#">Myinfo</a></li>
<li><a href="#">Views</a></li>
</ul>
</li>
<li><a href="#">Services</a></li>
<li><a href="#">Products</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>
<li><a href="#"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
</ul>
</div>
</div>
</nav>
</body>
</html>

Comments or Responses

Login to post response