Javascript code for Bootstrap Sidebar menu not working - javascript

I have a Sidebar / Menu that I am working with. It has been created with Bootstrap, DJango, and Javascript.
Basically, I am trying to write Javascript so that when on clicks on a menu-item, the background changes color (dark blue), the icon change color (light green / turquoise) and it gets a type of "wedge"
Below is an example of a menu-item that has been chosen (Dashboard) along with menu-items that have not been chosen (Security and Messages). The "wedge" has a red arrow pointing to it.
Here is the HTML code that is being used:
[... snip ...]
<div class="page-container">
<div class="page-sidebar-wrapper">
<div class="page-sidebar navbar-collapse collapse">
<ul class="page-sidebar-menu page-header-fixed page-sidebar-menu-hover-submenu "
data-keep-expanded="false" data-auto-scroll="true" data-slide-speed="200">
<li class="nav-item start active open">
<a href="{% url 'mainadmin:dashboard' %}" class="nav-link nav-toggle">
<i class="fa fa-tachometer"></i>
<span class="title">Dashboard</span>
<span class="selected"></span>
<span class="arrow open"></span>
</a>
</li>
<li class="nav-item ">
<a href="{% url 'mainadmin:security' %}" class="nav-link nav-toggle">
<i class="fa fa-users"></i>
<span class="title">Security</span>
<span class="arrow"></span>
</a>
</li>
<li class="nav-item ">
<a href="{% url 'mainadmin:in_progress' %}" class="nav-link nav-toggle">
<i class="fa fa-comment"></i>
<span class="title">Messages</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="{% url 'mainadmin:in_progress' %}" class="nav-link ">
<span class="title">List All Messages</span>
</a>
</li>
<li class="nav-item ">
<a href="{% url 'mainadmin:in_progress' %}" class="nav-link ">
<span class="title">List My Messages</span>
<span class="badge badge-danger"></span>
</a>
</li>
</ul>
</li>
[... snip ...]
Here is the Javascript code:
<script>
$(document).ready(function () {
$('.nav-item a').click(function(e) {
$('.nav-item a').removeClass('selected');
$('.nav-item a').removeClass('arrow');
$('.nav-item a').removeClass('open');
$('.nav-item a').removeClass('active');
alert("I have gotten in");
var $parent = $(this).parent();
$parent.addClass('selected');
$parent.addClass('arrow');
$parent.addClass('open');
$parent.addClass('active');
e.preventDefault();
});
});
</script>
I do get the alert message - but - what happens is :
-> the background of the chosen menu-item does change color - which is correct
--> The icon of the chosen menu-item changes color (to light blue / turquoise) - which is correct
-> the tick of the arrow does not take place for the chosen menu-item :(
-> the old chosen menu item does not "de-select"
What am I doing wrong?
TIA
Hi #Joe Lissner
Thanks so much for the response!
I had to add the following to get the "wedge" portion to work. It required span tags
// REFERENCE: https://stackoverflow.com/questions/2013710/add-span-tag-within-anchor-in-jquery
$(this).append('<span class="selected"></span>');
$(this).append('<span class="arrow open"></span>');
While this works when clicking on the main-menu item, I'm not so lucky when it comes to clicking on sub-menu items. As of now, I am pretty much new to Javascript.
How would one get the sub-menu items to work?
Also, when clicking on an item, it does not go to the page specified in "href="
How would can one make changes to the code so that when the menu-item is clicked, it would go to the page specified in "href="
Again, thanks for the response :-)

You are removing the classes from the a tags, not the .nav-item elements.
Try this:
$(document).ready(function () {
$('.nav-item a').click(function(e) {
e.preventDefault(); // best practice to have this first, if you remove this line then the link will function as expected.
var $parent = $(this).parent();
var $arrow = $parent.find('.arrow');
$('.nav-item').removeClass('selected arrow open active'); // simplified
$('.nav-item .arrow').removeClass('open');
$('.nav-item .selected').detach(); // remove the span that was there before
alert("I have gotten in");
$parent.addClass('open active'); // simplified
$arrow.addClass('open').before('<span class="selected" />')
});
});
Edit - Fixed the issue with the arrow

Related

Add active class after page loading

I am trying to add an active class after page load. Here is my script. This script is working when I click. But when the page is loaded, the active class disappear.
<ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">
<li class="nav-item">
<a class="nav-link" href="{{url('/account')}}" target="_blank">
<i class="fas fa-fw fa-tachometer-alt"> account</i>
</li>
</ul>
$(document).ready(function(){
$(".nav-item a").on("click", function(){ $(".nav-item").find(".active").removeClass("active"); $(this).parent().addClass("active");});
});
I am trying to work with localStorage function not succeed .please suggest me what I have to do.
You can clean up your code in many ways:
use toggleClass instead of add/remove class
use .nav-link rather than .nav-item a for one, a will be any anchor element, not just the first child (you'd do better to do .nav-item > a), but that has a distinctive class (.nav-link) so use that
to assign a class on load, just do it and don't put it in the click event
$(document).ready(function() {
$('.nav-item').addClass('active'); // <-- how to add the class on page load
$(".nav-link").on("click", function() {
$(this).parent().toggleClass('active');
});
});
.active .nav-link::after {
content: " <==";
color: red;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
<div class="container">
<ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">
<li class="nav-item">
<a class="nav-link" href="{{url('/account')}}" target="_blank">
<i class="fas fa-fw fa-tachometer-alt"> account</i>
</a>
</li>
</ul>
</div>
You can check if the url has the href or not then you can trigger the click event for the <a> which has matched href ..
Try the next code
<ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">
<li class="nav-item">
<a class="nav-link" href="{{url('/account')}}" target="_blank">
<i class="fas fa-fw fa-tachometer-alt"> account</i>
</a>
</li>
</ul>
$(document).ready(function(){
$(".nav-item a").on("click", function(){
$(".nav-item.active").removeClass("active");
$(this).parent().addClass("active");
}).filter(function(){
return window.location.href.indexOf($(this).attr('href').trim()) > -1;
}).click();
});
Note about the code above ^^^^^:
The code above won't work as expected IF you have url http://website.com/account/thing and you have two <a> with hrefs /account and /account/thing both of <a> will get selected
To avoid this you can use data attribute
<ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">
<li class="nav-item">
<a class="nav-link" href="{{url('/account')}}" data-href="http://website.com/account" target="_blank">
<i class="fas fa-fw fa-tachometer-alt"> account</i>
</a>
</li>
</ul>
$(document).ready(function(){
$(".nav-item a").on("click", function(){
$(".nav-item.active").removeClass("active");
$(this).parent().addClass("active");
}).filter(function(){
return window.location.href == $(this).attr('data-href').trim();
}).click();
});
Note about the code above ^^^^^:
In <a> add data-href="http://website.com/account" replace http://website.com/account with the full url

How to override or redefine vue router?

My problems
Hi guys,
I am building a website that uses vuejs (vue, vuex, vue-router). Besides, I have used another template which is material dashboard (this template uses bootrsap4 and a custom js file).
At first, everything was very convenient, my vue-router worked perfectly. But when I checked the interface on my phone, there was a problem:
In this interface, the user menu in the upper right corner works with the vue-router normally, my page does not reload every time the url changes.
But when I changed the browser size, made it smaller and the user menu bar will now show as above. The problem now is that the links act like a normal anchor tag, and my page re-loads every time the URL changes.
Found the cause
This is the code of the user menu bar.
<!-- language-all: lang-html -->
<div class="collapse navbar-collapse justify-content-end">
<div class="navbar-form"></div>
<ul class="navbar-nav">
<li class="nav-item dropdown">
<a class="nav-link" href="javascript:;" id="navbarDropdownProfile" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="material-icons">person</i>
<p class="d-lg-none d-md-block">
Account
</p>
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdownProfile">
<router-link class="dropdown-item" to="/test">Profile</router-link>
<router-link class="dropdown-item" to="/another_one">Settings</router-link>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Log out</a>
</div>
</li>
</ul>
</div>
The problem is in the template's javascript custom file
They use a function that rewrites the menu bar whenever the window size gets smaller and
this may accidentally overwrite or disrupt the vue-router. The code is as follows:
initRightMenu: debounce(function() {
$sidebar_wrapper = $('.sidebar-wrapper');
if (!mobile_menu_initialized) {
$navbar = $('nav').find('.navbar-collapse').children('.navbar-nav');
mobile_menu_content = '';
nav_content = $navbar.html();
nav_content = '<ul class="nav navbar-nav nav-mobile-menu">' + nav_content + '</ul>';
navbar_form = $('nav').find('.navbar-form').get(0).outerHTML;
$sidebar_nav = $sidebar_wrapper.find(' > .nav');
// insert the navbar form before the sidebar list
$nav_content = $(nav_content);
$navbar_form = $(navbar_form);
$nav_content.insertBefore($sidebar_nav);
$navbar_form.insertBefore($nav_content);
$(".sidebar-wrapper .dropdown .dropdown-menu > li > a").click(function(event) {
event.stopPropagation();
});
// simulate resize so all the charts/maps will be redrawn
window.dispatchEvent(new Event('resize'));
mobile_menu_initialized = true;
} else {
if ($(window).width() > 991) {
// reset all the additions that we made for the sidebar wrapper only if the screen is bigger than 991px
$sidebar_wrapper.find('.navbar-form').remove();
$sidebar_wrapper.find('.nav-mobile-menu').remove();
mobile_menu_initialized = false;
}
}
}, 200),
What have I tried
I tried rewriting javascript in their js file as follows:
nav_content = $navbar.html(); // I turned this
// into this
nav_content = `<li class="nav-item dropdown">
<a class="nav-link" href="javascript:;" id="navbarDropdownProfile" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="material-icons">person</i>
<p class="d-lg-none d-md-block">
Account
</p>
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdownProfile">
<router-link class="dropdown-item" to="/test">Profile</router-link>
<router-link class="dropdown-item" to="another_one">Settings</router-link>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Log out</a>
</div>
</li>`
But it still does not work
To be more clear
I tried printing out nav_content, everything seems right. I think the problem is $nav_content = $(nav_content);
Is the problem I pointed out correct? If yes, I'd appreciate it if I got your advice, thank you.

Navbar active class resets on page load

Using bootstrap 4 and asp.net core for a personal project I've been tinkering with for the past couple of months. I've got a navbar in my _Layout that is shared across my entire site. I've also got some css that styles the navbar link text.
I'm trying to change the active class on the links so the currently-visited controller is highlighted with a different color. I'm using js to do this. The color is changing initially, so I'm sure that the js is adding the active class to the new link and removing it from the previous active link, but when the page finishes loading, they reset and the active class goes back to Home.
Here is my navbar in _Layout.cshtml:
<nav class="navbar navbar-toggleable-md navbar-inverse bg-inverse">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggler" aria-controls="navbarToggler" aria-expanded="false" aria-label="Toggle navigation">
<img src="~/images/logo1.png" width="40" height="40" alt="" />
</button>
<div class="collapse navbar-collapse" id="navbarToggler">
<ul class="nav navbar-nav mr-auto mt-2 mt-lg-0">
<li class="nav-item active">
<a class="nav-link" asp-action="Index" asp-controller="Home">Home<span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" asp-action="Index" asp-controller="aaaa">Aaaa</a>
</li>
<li class="nav-item">
<a class="nav-link" asp-action="Index" asp-controller="bbbb">Bbbb</a>
</li>
<li class="nav-item">
<a class="nav-link" asp-action="Index" asp-controller="cccc">Cccc</a>
</li>
<li class="nav-item">
<a class="nav-link" asp-action="Index" asp-controller="dddd">Dddd</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<button class="btn btn-outline-danger btn-sm"
type="submit" asp-action="Login" asp-controller="Account">
Login
</button>
</form>
</div>
Here is the js that I'm declaring in the #scripts section of _Layout:
$( '.navbar-inverse .navbar-nav a' ).on( 'click', function () {
$( '.navbar-inverse .navbar-nav' ).find( 'li.active' ).removeClass( 'active' );
$( this ).parent( 'li' ).addClass( 'active' );
});
And my css:
.navbar-inverse .navbar-nav .open > .nav-link,
.navbar-inverse .navbar-nav .active > .nav-link,
.navbar-inverse .navbar-nav .nav-link.open,
.navbar-inverse .navbar-nav .nav-link.active {
color: yellow;
}
Why is the active link being reset when the new page loads? I know the js is working because while the page is loading, "Home" is not yellow anymore, but the new link I clicked in the navbar is yellow. But when the loading is complete, the yellow goes back to Home. Any insights would be appreciated, I'm rather new at software development.
You're setting active on click. However, when the browser actually goes to that URL following the click, a completely different view is rendered. Therefore, there's no concept of anything having been set a certain way or done previously.
Instead, you need to either have your JS run onload, or simply just send the HTML with the correct item active in the first place, and throw away the JS. The easiest way to do that is something like:
#{ string url; }
Then for each nav link:
#{ url = Url.Action("Foo", "Bar"); }
<li class="#(Request.Path.StartsWith(url) ? "active" : null)">
Foo
</li>
Setting the url variable is mostly just a way to not repeat yourself with the action/controller for the link, since you need the link URL in two different places.
The meat is in the ternary. If the current URL path starts with this link's URL (which should cover both the scenario of being equal to and just being a parent of the current URL), then you apply the active class.
EDIT
Because of using StartsWith, a link for "Home" will basically always be set as active, since every URL would start with /. You probably want to make an exception on that link and instead just do:
#{ url = Url.Action("Index", "Home"); }
<li class="#(Request.Path == url ? "active" : null)">
Home
</li>
Then, that link will only be marked active if the URL is actually /.
Thanks to #Chris Pratt for his guidance. I got this working albeit with a couple of changes, possibly due to me changing my mind on the navbar and moving to a tabbed navbar (like Twitter's mobile app uses). Here's my navbar code in _Layout.cshtml:
<!--navbar-->
#{ string url; }
<ul class="nav navbar-dark bg-dark nav-tabs nav-fill">
#{ url = Url.Action("Index", "Home"); }
<li class="nav-item">
<a class="nav-link #(Context.Request.Path == url ? "active" : null)" href="#url">Home</a>
</li>
#{ url = Url.Action("Index", "Spells"); }
<li class="nav-item">
<a class="nav-link #(Context.Request.Path.StartsWithSegments(url) ? "active" : null)" href="#url">Spells</a>
</li>
#{ url = Url.Action("Index", "Crits"); }
<li class="nav-item">
<a class="nav-link #(Context.Request.Path.StartsWithSegments(url) ? "active" : null)" href="#url">Crits</a>
</li>
#{ url = Url.Action("Index", "Journal"); }
<li class="nav-item">
<a class="nav-link #(Context.Request.Path.StartsWithSegments(url) ? "active" : null)" href="#url">Journal</a>
</li>
</ul>
Now that the active class switching is working as expected, I can add some styling, and replace the text with icons that I'll make.
Gave you an upvote, Chris Pratt, but my rep is too low to show it publicly for now. Thanks again.

Selecting Closest Match using jQuery

I am having trouble selecting the closest match. I already tried .closest, .next, and .nextall; I also tried using (this), but I think I'm using them incorrectly.
Here's what I want to acheive:
When .show is clicked, the closest .list-content will toggle and the closest toggleClass icon-rotate-180 too.
<ul class="list-unstyled">
<li class="list-menu">
<a href="javascript:void(0);" class="show">
Date of Operations
<i class="icon-chevron-down pull-right"></i>
</a>
</li>
<li class="list-content">Hidden Content until Clicked</li>
<li class="list-menu">
<a href="javascript:void(0);" class="show">
Date of Operations
<i class="icon-chevron-down pull-right"></i>
</a>
</li>
<li class="list-content">Hidden Content until Clicked</li>
</ul>
<script>
$(document).ready(function() {
$(".list-content").hide();
$(".show").click(function() {
$(".icon-chevron-down").toggleClass("icon-rotate-180");
$(".list-content").toggle();
});
});
</script>
Firstly, your HTML is invalid as you cannot have a div element as a direct child of a ul. With that in mind, try this:
<ul class="list-unstyled">
<li class="list-menu">
<a href="#" class="show">
Date of Operations
<i class="icon-chevron-down pull-right"></i>
</a>
<div class="list-content">Hidden Content until Clicked</div>
</li>
<li class="list-menu">
<a href="#" class="show">
Date of Operations
<i class="icon-chevron-down pull-right"></i>
</a>
<div class="list-content">Hidden Content until Clicked</div>
</li>
</ul>
$(".show").click(function(e) {
e.preventDefault();
$(".icon-chevron-down", this).toggleClass("icon-rotate-180");
$(".list-content", $(this).closest('li')).toggle();
});
ul/li is the wrong case here. The second li is in relation to the first li. Please use dl, dd and dt instead - this is not the perfect match but better than ul/li!
a is for links but you dont call a url. Please use the dd itself or a span so you dont need the javascript:void(0); and no e.preventDefault();.
Date of Operations
Hidden Content until Clicked
<dd class="list-menu show">
Date of Operations
<i class="icon-chevron-down pull-right"></i>
</dd>
<dt class="list-content">Hidden Content until Clicked</dt>
$(".show").click(function(e) {
$(this).closest(".icon-chevron-down").toggleClass("icon-rotate-180");
$(this).next("dt.list-content").toggle();
});
(i copied a part of RoyMcCrossan's answer from Selecting Closest Match using jQuery)
Sorry structure broken, looks like a bug in Stackoverflow.

Bootstrap close responsive menu "on click"

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>

Categories

Resources