I am trying to create a Bootstrap dropdown menu with two sub-menus. My problem is that the dropdowns are dynamically created after the document is loaded, and don't respond to how I would normally get them to work.
How I would normally go about it would be
$(document).ready(function(){
addItem(); //adds the first instance of the drop down
$('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(e){
e.stopPropagation();
e.preventDefault();
$(this).siblings().removeClass("open");
$(this).parent().toggleClass("open");
});
});
But this obviously doesn't work for dynamically created content. I saw elsewhere online that this would work for dynamic content;
//still has first instance of dropdown, just later in the doc
$(document).on('click', 'ul.dropdown-menu [data-toggle=dropdown]', function(e){
e.stopPropagation();
e.preventDefault();
$(this).siblings().removeClass("open");
$(this).parent().toggleClass("open");
});
but for the life of me, I can't figure out why this doesn't work. What I'm seeing is that it is adding the open class to the sub-menu, but toggle the parent menu(not stopping propagation?) So, my question is, why doesn't the second one execute as expected, and how can I make it?
List structure for reference:
<div class="dropdown open">
<button id="select0" class="btn new-btn" data-toggle="dropdown" aria-expanded="true">Select Your Item <span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a class="sub" data-toggle="dropdown">Item 1</a>
<ul class="dropdown-menu sub-menu">
<li><a data-def-cost="6">Item 1.1</a></li>
<li><a data-def-cost="8">Item 1.2</a></li>
</ul>
</li>
<li><a class="sub" data-toggle="dropdown">Item 2</a>
<ul class="dropdown-menu sub-menu">
<li><a data-def-cost="5">Item 2.1</a></li>
<li><a data-def-cost="3">Item 2.2</a></li>
</ul>
</li>
<li><a data-plu="xyz" data-def-cost="8.00">Item 3</a></li>
<li><a data-plu="xyz" data-def-cost="8.00">Item 4</a></li>
<li><a data-plu="xyz" data-def-cost="10.00">Item 5</a></li>
<li class="dropdown-header">Other Items</li>
<li><a data-plu="143">Item 6</a></li>
<li><a data-plu="xyz">Item 7</a></li>
<li><a data-plu="xyz">Item 8</a></li>
</ul>
<input type="text" class="hidden" name="input1">
<input type="text" class="hidden" name="otherinput1">
</div>
$(this).siblings() points to an ul element, however, the .open class is supposed to be added to the parent li : http://getbootstrap.com/javascript/#dropdowns-usage.
Via data attributes or JavaScript, the dropdown plugin toggles hidden content (dropdown menus) by toggling the .open class on the parent list item.
Here is a suggestion (inspired by the following code snippet : Multi-Level Dropdowns) :
$(document).ready(function () {
// this variable keeps track of the last open menus
// in order to close them when another link is clicked
// or when the entire dropdown is closed
var open;
$("#my-dropdown").on("hide.bs.dropdown", function () {
if (open) open.removeClass("open");
});
$(".dropdown-submenu > a").on("click", function (e) {
if (open) open.removeClass("open");
open = $(this).parents(".dropdown-submenu");
open.addClass("open");
e.stopPropagation();
e.preventDefault();
});
});
.dropdown-submenu {
position: relative;
}
.dropdown-submenu .dropdown-menu {
top: 0;
left: 100%;
margin-top: -1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<div class="dropdown" id="my-dropdown">
<button type="button" data-toggle="dropdown">
Dropdown trigger
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li>Action 1</li>
<li>Action 2</li>
<li class="dropdown-submenu">
Submenu 1
<ul class="dropdown-menu">
<li>Action 1.1</li>
<li>Action 1.2</li>
</ul>
</li>
<li class="dropdown-submenu">
Submenu 2
<ul class="dropdown-menu">
<li>Action 2.1</li>
<li>Action 2.2</li>
<li class="dropdown-submenu">
Submenu 2.3
<ul class="dropdown-menu">
<li>Action 2.3.1</li>
<li>Action 2.3.2</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
Unsure as to efficiency of my solution, but I rearranged the order a bit, and forced the parent to stay open
$(document).on('click', 'ul.dropdown-menu [data-toggle=dropdown]', function(e){
$(this).siblings().removeClass("open");
$(this).parent().addClass("open");
$(this).parent().parent().parent().addClass("open");
e.stopPropagation();
e.preventDefault();
});
and this solved my issue
use one of these below lines.
$(this).siblings('.dropdown-menu').removeClass('open');
$(this).next('.dropdown-menu').removeClass('open');
What I would like to happen: The first three list items in the nav bar should correspond to the first three content items in the content area. The three list items in the dropdown should correspond to the remaining three content items. Hovering over the dropdown icon should display the list but the dropdown icon shouldn't link to anywhere.
What's actually happening: The first three list items work properly and link to the first three content items. The dropdown box animates properly, but the items in it all link to the 4th content item. Clicking the dropdown box's icon also links to the 4th item.
Here is the code (A lot of the code is generated, so I grabbed the code from FireBug, which is why the "uk-active" classes and "aria-hidden" attributes are there):
<nav class="uk-navbar">
<ul class="uk-navbar-nav" data-uk-switcher="{connect:'#content-area'}">
<li class="uk-active" aria-expanded="true">
Dashboard
</li>
<li aria-expanded="false">
Summary
</li>
<li aria-expanded="false">
Details
</li>
<li id="settings-btn-container" class="uk-parent" data-uk-dropdown="" aria-expanded="false" aria-haspopup="true">
<a href="">
<i class="uk-icon-cog"></i>
</a>
<div id="settings-dropdown-container" class="uk-dropdown uk-dropdown-navbar uk-dropdown-bottom" aria-hidden="true" style="top: 40px; left: 0px;" tabindex="">
<ul id="settings-dropdown" class="uk-nav uk-nav-navbar">
<li>
Upgrade
</li>
<li>
Configure
</li>
<li>
Settings
</li>
</ul>
</div>
</li>
</ul>
</nav>
<ul id="content-area" class="uk-switcher">
<li id="content-dashboard" class="parent.uk-container uk-container-center uk-active" aria-hidden="false">...</li>
<li id="content-summary" aria-hidden="true">...</li>
<li id="content-details" aria-hidden="true">...</li>
<li id="content-upgrade" aria-hidden="true">...</li>
<li id="content-config" aria-hidden="true">...</li>
<li id="content-settings" aria-hidden="true">...</li>
</ul>
Basically, the "on click" event handler for the 4th content item is getting added to the "settings-btn-container" list item and no event handlers are getting added to the list items under the dropdown. I can't figure out how to get the event handlers to bind to the dropdown list items instead.
Try being more explicit to the UIkit Switcher component about what constitutes a "toggle".
In the snippet below, I've used these settings:
{
connect: '#content-area',
toggle: '.toggle-link'
}
The default value for toggle, in the UIkit Switcher component is >*, which you'll probably recognize as a selector for "the first immediate child element of any type". Since the links in your dropdown are not immediate descendants, no Switcher events were fired when they were clicked.
By broadening the "toggle" definition to all .toggle-link elements in the switcher, each of your links gets mapped to the corresponding <li> in the #content-area element.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/2.27.2/js/uikit.js"></script>
<link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/uikit/2.27.2/css/uikit.min.css'>
<nav class="uk-navbar">
<ul id="switcher-menu" class="uk-navbar-nav" data-uk-switcher="{connect: '#content-area', toggle: '.toggle-link'}">
<li class="uk-active toggle-link">Dashboard</li>
<li class="toggle-link">Summary</li>
<li class="toggle-link">Details</li>
<li id="settings-btn-container" class="uk-parent" data-uk-dropdown>
<i class="uk-icon-cog"></i>
<div id="settings-dropdown-container" class="uk-dropdown uk-dropdown-navbar uk-dropdown-bottom">
<ul id="settings-dropdown" class="uk-nav uk-nav-navbar">
<li class="toggle-link">Upgrade</li>
<li class="toggle-link">Configure</li>
<li class="toggle-link">Settings</li>
</ul>
</div>
</li>
</ul>
</nav>
<div class="uk-container uk-container-center">
<ul id="content-area" class="uk-switcher">
<li class="uk-active">... (Dashboard)</li>
<li>... (Content Summary)</li>
<li>... (Content Details)</li>
<li>... (Content Upgrade)</li>
<li>... (Content Config)</li>
<li>... (Content Settings)</li>
</ul>
</div>
I am trying to open a dropdown on hover in Bootstrap but somehow it's not working. I suspect that my jQuery code is wrong but I can't figure out what?
Here is my HTML:
<a href="#" id="dropdown-filter" data-target="#" data-toggle="dropdown">
<button type="button" class="btn btn-primary">Filters</button>
</a>
<ul class="dropdown-menu pull-right" role="menu">
<li>
<div class="results-filter">
Content goes here
</div>
</li>
</ul>
and my jQuery:
jQuery('#dropdown-filter').hover(function() {
jQuery(this).find('.dropdown-menu').stop(true, true).delay(100).fadeIn();
}, function() {
jQuery(this).find('.dropdown-menu').stop(true, true).delay(100).fadeOut();
});
It works when I click on top, but not when I hover.
jQuery(this).find('.dropdown-menu') won't work here as .dropdown-menu is not a child of <a>-#dropdown-filter.
.find() searches for children.
Use jQuery(this).next('.dropdown-menu')...
On "PRODUCTS" click I slide up a white div (as seen in attached). When in responsive (mobile and tablet), I would like to automaticly close the responsive navbar and only show the white bar.
I tried:
$('.btn-navbar').click();
also tried:
$('.nav-collapse').toggle();
And it does work. However in desktop size, it is also called and does something funky to the menu where it shrinks for a second.
Any ideas?
You don't have to add any extra javascript to what's already included with bootstraps collapse option. Instead simply include data-toggle and data-target selectors on your menu list items just as you do with your navbar-toggle button. So for your Products menu item it would look like this
<li>Products</li>
Then you would need to repeat the data-toggle and data-target selectors for each menu item
EDIT!!!
In order to fix overflow issues and flickering on this fix I'm adding some more code that will fix this and still not have any extra javascript. Here is the new code:
<li>Products</li>
<li>Products</li>
Here it is at work http://jsfiddle.net/jaketaylor/84mqazgq/
This will make your toggle and target selectors specific to screen size and eliminate glitches on the larger menu. If anyone is still having issues with glitches please let me know and I'll find a fix.
Thanks
EDIT: In the bootstrap v4.1.3 & v5.0 I couldnt use visible/hidden classes. Instead of hidden-xs use d-none d-sm-block and instead of visible-xs use d-block d-sm-none.
EDIT: In bootstrap v5, Instead of data-toggle use data-bs-toggle and instead of data-target use data-bs-target.
I've got it to work with animation!
Menu in html:
<div id="nav-main" class="nav-collapse collapse">
<ul class="nav">
<li>
<a href='#somewhere'>Somewhere</a>
</li>
</ul>
</div>
Binding click event on all a elements in navigation to collapse menu (Bootstrap collapse plugin):
$(function(){
var navMain = $("#nav-main");
navMain.on("click", "a", null, function () {
navMain.collapse('hide');
});
});
EDIT
To make it more generic we can use following code snippet
$(function(){
var navMain = $(".navbar-collapse"); // avoid dependency on #id
// "a:not([data-toggle])" - to avoid issues caused
// when you have dropdown inside navbar
navMain.on("click", "a:not([data-toggle])", null, function () {
navMain.collapse('hide');
});
});
I think you are all over engineering..
$('.navbar-collapse ul li a').click(function(){
$('.navbar-toggle:visible').click();
});
EDIT: To take care of sub menus, make sure their toggle anchor has the dropdown-toggle class on it.
$(function () {
$('.navbar-collapse ul li a:not(.dropdown-toggle)').click(function () {
$('.navbar-toggle:visible').click();
});
});
EDIT 2: Add support for phone touch.
$(function () {
$('.navbar-collapse ul li a:not(.dropdown-toggle)').bind('click touchstart', function () {
$('.navbar-toggle:visible').click();
});
});
I really liked Jake Taylor's idea of doing it without additional JavaScript and taking advantage of Bootstrap's collapse toggle. I found you can fix the "flickering" issue present when the menu isn't in collapsed mode by modifying the data-target selector slightly to include the in class. So it looks like this:
<li>Products</li>
I didn't test it with nested dropdowns/menus, so YMMV.
just to be complete, in Bootstrap 4.0.0-beta using .show worked for me...
<li>
Products
</li>
I'm assuming you have a line like this defining the nav area, based on Bootstrap examples and all
<div class="nav-collapse collapse" >
Simply add the properties as such, like on the MENU button
<div class="nav-collapse collapse" data-toggle="collapse" data-target=".nav-collapse">
I've added to <body> as well, worked. Can't say I've profiled it or anything, but seems a treat to me...until you click on a random spot of the UI to open the menu, so not so good that.
DK
This works, but does not animate.
$('.btn-navbar').addClass('collapsed');
$('.nav-collapse').removeClass('in').css('height', '0');
In the HTML I added a class of nav-link to the a tag of each navigation link.
$('.nav-link').click(
function () {
$('.navbar-collapse').removeClass('in');
}
);
this solution have a fine work, on desktop and mobile.
<div id="navbar" class="navbar-collapse collapse" data-toggle="collapse" data-target=".navbar-collapse collapse">
Just to spell out user1040259's solution, add this code to your $(document).ready(function() {});
$('.nav').click( function() {
$('.btn-navbar').addClass('collapsed');
$('.nav-collapse').removeClass('in').css('height', '0');
});
As they mention, this doesn't animate the move... but it does close the nav bar on item selection
For those using AngularJS and Angular UI Router with this, here is my solution (using mollwe's toggle).
Where ".navbar-main-collapse" is my "data-target".
Create directive:
module.directive('navbarMainCollapse', ['$rootScope', function ($rootScope) {
return {
restrict: 'C',
link: function (scope, element) {
//watch for state/route change (Angular UI Router specific)
$rootScope.$on('$stateChangeSuccess', function () {
if (!element.hasClass('collapse')) {
element.collapse('hide');
}
});
}
};
}]);
Use Directive:
<div class="collapse navbar-collapse navbar-main-collapse">
<your menu>
This should do the trick.
Requires bootstrap.js.
Example => http://getbootstrap.com/javascript/#collapse
$('.nav li a').click(function() {
$('#nav-main').collapse('hide');
});
This does the same thing as adding 'data-toggle="collapse"' and 'href="yournavigationID"' attributes to navigation menus tags.
I'm using the mollwe function, although I added 2 improvements:
a) Avoid the dropdown closing if the link clicked is collapsed (including other links)
b) Hide the dropdown too, if you are clicking the visible web content.
jQuery.fn.exists = function() {
return this.length > 0;
}
$(function() {
var navMain = $(".navbar-collapse");
navMain.on("click", "a", null, function() {
if ($(this).attr("href") !== "#") {
navMain.collapse('hide');
}
});
$("#content").bind("click", function() {
if ($(".navbar-collapse.navbar-ex1-collapse.in").exists()) {
navMain.collapse('hide');
}
});
});
Not the newest thread but i searched for a solution for the same Problem and found one (a mix of some others).
I gave the NavButton:
<type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> ...
an id / Identifier like:
<button id="navcop" type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
Not the finest "Idea" - but: Works for me!
Now you can check up the visibility of your button (with jquery) like:
var target = $('#navcop');
if(target.is(":visible")){
$('#navcop').click();
}
(NOTE: This is just a Code snipped ! I used a "onclick" Event on my Nav Links! (Starting a AJAX Reguest.)
The result is: If the Button is "visible" it got "clicked" ... So: No Bug if you use the "Fullscreen view" of Bootstrap (width of over 940px).
Greetings
Ralph
PS: It works fine with IE9, IE10 and Firefox 25. Didnt checked up others - But i can't see a Problem :-)
This worked for me. I have done like, when i click on the menu button, im adding or removing the class 'in' because by adding or removing that class the toggle is working by default. 'e.stopPropagation()' is to stop the default animation by bootstrap(i guess) you can also use the 'toggleClass' in place of add or remove class.
$('#ChangeToggle').on('click', function (e) {
if ($('.navbar-collapse').hasClass('in')) {
$('.navbar-collapse').removeClass('in');
e.stopPropagation();
} else {
$('.navbar-collapse').addClass('in');
$('.navbar-collapse').collapse();
}
});
Bootstrap 4 solution without any Javascript
Add attributes data-toggle="collapse" data-target="#navbarSupportedContent.show" to the div <div class="collapse navbar-collapse">
Make sure you provide the correct id in data-target
<div className="collapse navbar-collapse" id="navbarSupportedContent" data-toggle="collapse" data-target="#navbarSupportedContent.show">
.show is to avoid menu flickering in large resolutions
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<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" data-toggle="collapse" data-target="#navbarSupportedContent.show">
<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>
</nav>
I found an easy solution for this. Just add the toggle code of the button on the navbar links too.
In the below example is the code data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02".
This will close the menu when clicked and follow the link
<!--data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02" from toggle button -->
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02" aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse nav-format-mobile" id="navbarTogglerDemo02">
<ul class="navbar-nav ms-auto mb-2 mb-lg-0"> <!--https://stackoverflow.com/a/65365121/5763690-->
<li class="nav-item">
<!--data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02" from toggle button to nav item -->
<a class="nav-link" aria-current="page" [routerLink]="'about'" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02">About</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">
Services
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" [routerLink]="'services'" fragment="why-us" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02">Overview</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" [routerLink]="'services'" fragment="project" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02">For companies</a></li>
<li><a class="dropdown-item" [routerLink]="'services'" fragment="startups" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02">For Startups</a></li>
<li><a class="dropdown-item" [routerLink]="'/services'" fragment="ngos" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02">For NGOs</a></li>
</ul>
</li>
<li class="nav-item">
<!--data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02" from toggle button to nav item -->
<a class="nav-link" [routerLink]="'products'" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02">Products</a>
</li>
<li class="nav-item">
<a class="nav-link" [routerLink]="'career'" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02">Career</a>
</li>
<li class="nav-item">
<a class="nav-link" [routerLink]="'contact'" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02">Contact</a>
</li>
</ul>
</div>
You cau use
ul.nav {
display: none;
}
This will by default close the navbar.
Please let me know anybody finds this usefull
If for example your toggle-able icon is visible only for extra small devices, then you could do something like this:
$('[data-toggle="offcanvas"]').click(function () {
$('#side-menu').toggleClass('hidden-xs');
});
Clicking [data-toggle="offcanvas"] will add bootstrap's .hidden-xs to my #side-menu which will hide the side-menu content, but will become visible again if you increase the window size.
$('.navbar-toggle').trigger('click');
if menu html is
<div id="nav-main" class="nav-collapse collapse">
<ul class="nav">
<li>
<a href='#somewhere'>Somewhere</a>
</li>
</ul>
</div>
on nav toggle 'in' class is added and removed from the toggle. check if responsive menu is opened then perform the close toggle.
$('.nav-collapse .nav a').on('click', function(){
if ( $( '.nav-collapse' ).hasClass('in') ) {
$('.navbar-toggle').click();
}
});
Tuggle Nav Close, IE browser compatible answer, without any console error.
If you are using bootstrap, use this
$('.nav li a').on('click', function () {
if ($("#navbar").hasClass("in")) {
$('.navbar-collapse.in').show();
}
else {
$('.navbar-collapse.in').hide();
}
})
I tried the other suggestions in my Vue.js 3 app, however my vue-router router-links wouldn't work anymore.
I created a small function to click the menu toggle, if the menu had the "show" class. This worked great for me in all cases.
<template>
...
<div
id="navbarNavigation"
class="collapse navbar-collapse"
>
<ul
class="navbar-nav me-auto mb-2 mb-lg-0"
>
<li class="nav-item">
<router-link
:to="route.url"
class="nav-link"
#click="closeMenu('navbarNavigation')"
>
My route name
</router-link>
</li>
</ul>
</div>
...
</template>
<script>
setup (props) {
const closeMenu = (id) => {
const menuShown = document.getElementById(id).classList.contains('show')
if (menuShown) {
const menuToggle = document.getElementsByClassName('navbar-toggler')[0]
menuToggle.click()
}
}
return { closeMenu }
}
</script>
For peeps looking for a solution concerning Vue 3 router-link with Bootstrap 5 + data-bs-attributes:
Using data-bs-attributes to toggle the nav directly on a Vue-router-link doesn't seem to work - so instead you need to wrap each of your nav-links in a parent element if not already done (an li would be the obvious choice) and apply the relevant data-bs-attributes on that element.
In short - instead of this:
<li class="nav-item">
<router-link
to="/galaxy"
class="nav-link d-flex"
data-bs-toggle="collapse"
data-bs-target="#navbarCollapse.show"
>
<v-icon name="gi-galaxy" size="1" class="align-middle" scale="1.5" />
<span class="flex-fill align-middle text-start ms-3 ms-lg-1">The Galaxy</span>
</router-link>
</li>
Use this:
<li class="nav-item" data-bs-toggle="collapse" data-bs-target="#navbarCollapse.show">
<router-link to="/galaxy" class="nav-link d-flex">
<v-icon name="gi-galaxy" class="align-middle" scale="1.5" />
<span class="flex-fill align-middle text-start ms-3 ms-lg-1">The Galaxy</span>
</router-link>
</li>