Mobile menu doesn't collapse when a menu item is clicked - javascript

I'm having problem with a template where mobile menu doesn't collapse when a menu item is clicked. Tried to solve it adding extra class, extra ID's but persist. It only closes/hide when clicking again on hamburger icon. And this is particularly annoying...
The navbar html code is:
<!-- Fixed navbar -->
<div class="navbar navbar-smak navbar-fixed-top" id="navbar" role="navigation">
<div class="container">
<div class="navbar-header">
<a class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"><i class="fa fa-bars"></i></a>
<h1><a class="navbar-brand animate" href="#home">TEST SITE</a></h1>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right animate">
<li><a class="btn-navbar" href="#home">Home</a></li>
<li>Blog</li>
<li>Contacto</li>
</ul>
</div>
<!--/.nav-collapse -->
</div>
</div>
This is the dummy html file I'm working on, feel free to download and check it: https://aleare.com.ar/testing3/index2tst.html
This is the function that handle the collapsing menu:
$('a[href*=#]').each(function () {
if (filterPath(location.pathname) == filterPath(this.pathname) && location.hostname == this.hostname && this.hash.replace(/#/, '')) {
var $targetId = $(this.hash),
$targetAnchor = $('[name=' + this.hash.slice(1) + ']');
var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
if ($target) {
$(this).click(function () {
//Hack collapse top navigation after clicking
topMenu.parent().attr('style', 'height:0px').removeClass('in'); //Close navigation
$('.navbar .btn-navbar').addClass('collapsed');
var targetOffset = $target.offset().top - 52;
$('html, body').animate({
scrollTop: targetOffset
}, 800);
return false;
});
}
}
});
Does someone know why it's failing?

You must have a little more markup, e.g. topMenu and filterPath.
However, if I understand your question correctly it sounds like you want the mobile menu to toggle closed when you select an item from the mobile menu. I am not using your code, but borrowed a navbar from the Bootstrap examples and added a little extra code to just close the menu when you click on a link in the menu. I would not be surprised if there is something like that built into bootstrap, which I assume you are using ? If not, you can probably do something similar by triggering a click on the hamburger when "appropriate":
$('.nav-link:not(.dropdown-toggle), .dropdown-item').each(function () {
$(this).on("click", function(e) {
$(".navbar-toggler").trigger("click");
alert($(this).attr("href"));
});
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha256-YLGeXaapI0/5IgZopewRJcFXomhRMlYYjugPLSyNjTY=" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css" integrity="sha256-UzFD2WYH2U1dQpKDjjZK72VtPeWP50NoJjd26rnAdUI=" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha256-CjSoeELFOcH0/uxWu6mC/Vlrc1AARqbm/jiiImDGV3s=" crossorigin="anonymous"></script>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#home">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#link">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#action">Action</a>
<a class="dropdown-item" href="#another">Another action</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#soemthingelse">Something else here</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#">Disabled</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
<div class="col">
2 of 3
</div>
<div class="col">
3 of 3
</div>

Related

using element of one div from another div using javascript

I have a file, and there is a fragment for navbar. In the navbar, we have listItems, and based on the click of those listItems, we plan to open another subnavigationbar below it.
To achieve this, I have the following code:
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org"
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<body>
<div>
<div th:fragment="navbar">
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<button class="navbar-toggler" type="button" data-toggle="collapse"
data-target="#navbarTogglerDemo03"
aria-controls="navbarTogglerDemo03" aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse">
<ul class="navbar-nav mr-auto mt-2 mt-lg-0">
<li class="nav-item active"><a id="movies"
th:class="(${#httpServletRequest.requestURI}=='/movies') ? 'nav-link active' : 'nav-link'"
href="#subNavbarId">Movies</a></li> <!-- href fails -->
<li class="nav-item"><a id="hr"
th:class="(${#httpServletRequest.requestURI}=='/info') ? 'nav-link active' : 'nav-link'"
href="/info">Info</a></li>
</ul>
</div>
<ul class="nav navbar-nav navbar-right">
<div sec:authorize="isAuthenticated()">
Logged in: <span sec:authentication="name"></span>
</div>
</ul>
</nav>
<script type="text/javascript">
var projects = document.getElementById("movies");
var subNavBar = document.getElementById("subNavbarId"); //Failure
projects.addEventListener("click", function() {
subNavBar.style = "display:block;"
})
</script>
</div>
<div class = "subNavClass" id="subNavbarId" th:fragment="subnavbar" style="display: none;">
<nav id="navbar-nav ms-auto" class="navbar navbar-expand-lg"
style="background-color: #F5F5F5;">
<div class="collapse navbar-collapse">
<a class="navbar-brand px-5"></a>
<ul class="navbar-nav mr-auto mt-2 mt-lg-0">
<li class="nav-item"><a id="subnavbar-content"
href="/movieList"> movieList</a></li>
</ul>
</div>
</nav>
<script type="text/javascript">
var subNavBar = document.getElementById("subNavbarId");
subNavBar.addEventListener("mouseleave", function() {
subNavBar.style = "display:none;"
})
</script>
</div>
</div>
</body>
</html>
I want to have a scenario, where I click the "movie" on the navbar, and I get a subnavbar displayed with movieList. Similarly, when I click somewhere outside, the subnavbar fades away.
Guide me here.
PS: total noob
your subNavBar.style = "display:block;" looks wrong.
it should be subNavBar.style.display = "block";
According to the Bootstrap documentation, you can use a dropdown :
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<div class="btn-group">
<button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
Action
</button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">An action</a></li>
<li><a class="dropdown-item" href="#">Another action</a></li>
<li><a class="dropdown-item" href="#">Something else here</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="#">Separated link</a></li>
</ul>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
By the way, avoid changing css with javascript. You can make a css class and toggle it. Because you use Bootstrap, you can toggle the d-none provided class :
subNavBar.classList.toggle("d-none");

Collapse the Bootstrap burger menu when you click on a scrollspy link

How can you collapse the menu of a Bootstrap burger when you click on a scrollspy link?
When viewing my website on a smartphone, the bootstrap nav is reduced to a burger menu. If you click on a link that leads to a specific place in my index.html (such as #aboutMe) and not to an external page, then the navigation remains unfolded. I want it to collapse again afterwards.
You can view the code on: https://github.com/senkvalentin/personal_page or visit the website on: https://senkvalentin.com/
Here is a part of my html:
.h-100vh{
height:100vh;
}
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" />
<div data-spy="scroll" data-target=".navbar" data-offset="50">
<div class="container">
<div class="row">
<nav class="navbar fixed-top navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="/"><img src="./img/logo.png" alt="">
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link" aria-current="page" href="#home">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#aboutMe">About</a>
</li>
<li class="nav-item">
<a class="nav-link" aria-current="page" href="#projectsList">Projects</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Admin
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="!#" target="_blank">Server - Info</a></li>
<li><a class="dropdown-item" href="#" target="_blank">Mail - Server</a></li>
<li><a class="dropdown-item" href="#" target="_blank">Mail - Server</a></li>
<li><a class="dropdown-item" href="!#" target="_blank">Cloud - Server</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
</div>
<div id="home" class="h-100vh bg-warning">Home</div>
<div id="aboutMe" class="h-100vh bg-success">About Me</div>
<div id="projectsList" class="h-100vh bg-primary">Project</div>
I already looked at: How to hide collapsible Bootstrap navbar on click
And: Bootstrap panel-collapse collapses when you click on a link inside it is clicked
but nothing worked.
I'm using the latest version of jQuery and Bootstrap version 5.0.1:
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
In Jquery simply trigger click on the navbar-toggler button when link is clicked
$('.nav-link').click(function(){
$('.navbar-toggler').click();
});
$('.nav-link').click(function(){
$('.navbar-toggler').click();
});
.h-100vh{
height:100vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" />
<div data-spy="scroll" data-target=".navbar" data-offset="50">
<div class="container">
<div class="row">
<nav class="navbar fixed-top navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="/"><img src="./img/logo.png" alt="">
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link" aria-current="page" href="#home">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#aboutMe">About</a>
</li>
<li class="nav-item">
<a class="nav-link" aria-current="page" href="#projectsList">Projects</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Admin
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="!#" target="_blank">Server - Info</a></li>
<li><a class="dropdown-item" href="#" target="_blank">Mail - Server</a></li>
<li><a class="dropdown-item" href="#" target="_blank">Mail - Server</a></li>
<li><a class="dropdown-item" href="!#" target="_blank">Cloud - Server</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
</div>
<div id="home" class="h-100vh bg-warning">Home</div>
<div id="aboutMe" class="h-100vh bg-success">About Me</div>
<div id="projectsList" class="h-100vh bg-primary">Project</div>
You first need to select all .nav-link excluding .dropdown-toggle.
Then, assign an event listener to toggle the .navbar-collapse on click:
$(document).ready(() => {
let $navlinks = $('.nav-link').not('.dropdown-toggle');
// console.log($navlinks)
$navlinks.click((e) => {
$(e.target).closest('.navbar').find('.navbar-collapse').collapse('toggle')
})
})
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/css/bootstrap.css">
<div data-spy="scroll" data-target=".navbar" data-offset="50">
<div class="container">
<div class="row">
<nav class="navbar fixed-top navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="/"><img src="./img/logo.png" alt="logo">
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link" aria-current="page" href="/">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#aboutMe">About</a>
</li>
<li class="nav-item">
<a class="nav-link" aria-current="page" href="#projectsList">Projects</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Admin
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="!#" target="_blank">Server - Info</a></li>
<li><a class="dropdown-item" href="#" target="_blank">Mail - Server</a></li>
<li><a class="dropdown-item" href="#" target="_blank">Mail - Server</a></li>
<li><a class="dropdown-item" href="!#" target="_blank">Cloud - Server</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
</div>
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>

Bootstrap navbar not goin right and not open collapse [duplicate]

This question already has answers here:
Bootstrap 5 navbar align items right
(13 answers)
Navbar dropdown (collapse) is not working in Bootstrap 5
(11 answers)
Closed 1 year ago.
I am trying out Bootstrap for the first time, and it dose not seems like it is working as it should. I am trying out an a example. I will make the navbar links go to the right, and when the screen gose smaller it will be an hamburger menu (also on the right side). When i am trying this, the links gose not to the right (i tryd mr-auto and ml-auto for the ul), but when the screen go smaller, it dose form as a hamburger, but it dos not go to the right and it dose not open when i click it. So that is a big issue. Nothinh happens when i click the hamburger menu.
Am i doing something wrong with my links or code? I did download the bootstrap map's js and css and added to the project and linkin to it.
<head>
<meta charset="utf-8">
<title>Test</title>
<!-- bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet" />
<script src="js/bootstrap.min.js"></script>
</head>
<section class="containerOne">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo03" aria-controls="navbarTogglerDemo03" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="#">Navbar</a>
<div class="collapse navbar-collapse" id="navbarTogglerDemo03">
<ul class="navbar-nav ml-auto mt-2 mt-lg-0">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#">Disabled</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
Maybe this is the solution to your problem.
See the output here - https://demo.thelovekesh.repl.co/navba.html
<link href="https://getbootstrap.com/docs/5.0/dist/css/bootstrap.css" rel="stylesheet"/>
<script src="https://getbootstrap.com/docs/5.0/dist/js/bootstrap.bundle.min.js"></script>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">
<img src="https://www.pngjoy.com/tpl/img/logo.png" alt="">
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ms-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Dropdown
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="#">Action</a></li>
<li><a class="dropdown-item" href="#">Another action</a></li>
<li>
<hr class="dropdown-divider">
</li>
<li><a class="dropdown-item" href="#">Something else here</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
</li>
</ul>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
On a large screen, it looks like this.
You can also change the container and expand classes according to your needs.

Navbar is getting fit properly on the page react js

this is my code on bootstrap for navbar but it is not getting fit proper as u can see in png
it is coming at the center of the page i want it to cover the whole page .enter image description here
Brand
<div class="collapse navbar-collapse justify-content-between" id="navbarCollapse">
<div class="navbar-nav">
Home
Profile
<div class="nav-item dropdown">
Messages
<div class="dropdown-menu">
Inbox
Sent
Drafts
</div>
</div>
</div>
<form class="form-inline">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" />
<div class="input-group-append">
<button type="button" class="btn btn-secondary"><i class="fa fa-search"></i></button>
</div>
</div>
</form>
<div class="navbar-nav">
Login
</div>
</div>
</nav>
Here is an example.
In the example below I use container-fluid with a margin of 0 and padding of 0.
(You can do it without container-fluid wrapping your navbar, it is your choice for the sake of an example I will leave it in the snippet.)
Then if you want to put content inside of the navbar inside of the container. You can put div with a class of a container after starting the nav tag.
<head>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<style>
body {
background: #121212;
}
</style>
</head>
<body>
<div class="container-fluid m-0 p-0">
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="#">Brand</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#">Disabled</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</div>
</nav>
</div>
</body>

Bootstrap 4 navbar - collapse on nav-link click in vanilla JS

I am trying to make the Bootstrap 4 navbar only use vanilla js vs any jQuery. So far I've been able to get the toggler to trigger the nav to collapse and close on mobile. What I am now trying to figure out is how to make the navbar collapse when you click on a "nav-link"
Here is my HTML for the nav:
<nav class="navbar navbar-expand-lg navbar-light bg-light shadow-lg p-3 mb-5 bg-white fixed-top">
<div class="container">
<a class="navbar-brand" href="#">Start Bootstrap</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive"
aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item" >
<a class="nav-link" href="#about">About Us</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Browse Menu</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#visit">Contact</a>
</li>
</ul>
</div>
</div>
And my JS for the collapsing
(function () {
"use strict";
document.querySelectorAll("button.navbar-toggler")[0].addEventListener("click", function (event) {
var target = this.getAttribute("data-target");
var subbar = document.querySelectorAll(target)[0];
subbar.className = (subbar.className + " show").replace(/ show show/, "");
});
})();
But how do I make it so when a user clicks a <a class="nav-link" href="#"></a> it'll also collapse the navbar?
Thanks!
Since you are using custom code, it's unnecessary to have the target (data-target="#navbarResponsive") on the html. So we can rewrite the click handler to handle both elements, the toggler and the links. To toggle a class just use the method toggle on classList.
document.addEventListener("click", function(event) {
if (event.target.classList.contains("navbar-toggler-icon")) {
document.getElementById("navbarResponsive").classList.toggle("show");
} else if (event.target.classList.contains("nav-link")) {
document.getElementById("navbarResponsive").classList.remove("show");
}
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<nav class="navbar navbar-expand-lg navbar-light bg-light shadow-lg p-3 mb-5 bg-white fixed-top">
<div class="container">
<a class="navbar-brand" href="#">Start Bootstrap</a>
<button class="navbar-toggler" type="button" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item"><a class="nav-link" href="#about">About Us</a></li>
<li class="nav-item"><a class="nav-link" href="#">Browse Menu</a> </li>
<li class="nav-item"> <a class="nav-link" href="#visit">Contact</a> </li>
</ul>
</div>
</div>
</nav>
A possible solution for your question is to find all the .nav-links and add a click listener to remove the show class from the class list.
Also, you could simplify a bit your code using Element.classList.toggle(), something like:
(function() {
let subbar = document.getElementById("navbarResponsive");
document
.querySelectorAll("button.navbar-toggler")[0]
.addEventListener("click", function(event) {
subbar.classList.toggle("show");
});
for (let navItem of document.querySelectorAll("a.nav-link")) {
navItem.addEventListener("click", function(event) {
subbar.classList.remove("show");
});
}
})();
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<nav class="navbar navbar-expand-lg navbar-light bg-light shadow-lg p-3 mb-5 bg-white fixed-top">
<div class="container">
<a class="navbar-brand" href="#">Start Bootstrap</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="#about">About Us</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Browse Menu</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#visit">Contact</a>
</li>
</ul>
</div>
</div>
</nav>

Categories