Bootstrap navbar can't add active with JavaScript - javascript

I used Bootstrap , now I want to add active for the new navbar title when I jump to the new page, but the active cann't dynamic display , unless I manually refresh the new page.
The Html codes:
<ul class="nav navbar-nav " data-in="fadeInDown" data-out="fadeOutUp">
<li class="NavHead active"> Home</li>
<li class="NavHead"> Questions</li>
<li class="NavHead"> <a href="/tags" >Tags</a></li>
<li class="NavHead"> <a href="/knowledges" >Knowledges</a></li>
<li class="NavHead"> Company</li>
<li class="NavHead"> Activity</li>
</ul>
The JavaScript codes:
$(document).ready(function () {
'use strict';
$(function () {
$(".navbar-nav").find(".NavHead").each(function () {
if ($("a",this).attr("href") === window.location.pathname) {
$(this).addClass("active");
} else {
$(this).removeClass("active");
}
});
});
});
How should I to revise the JS?

You can use this code for add active class for the new navbar title when I jump to the new page
$('ul li a').click(function(){
$('li a').parent().removeClass("active");
$(this).parent().addClass("active");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Praveen is right, you have two document.ready function. Here's how I did it (just tweaking some part of your code):
$(function () {
$(".navbar-nav").find(".NavHead").each(function () {
if ($(this).children('a').attr("href") === window.location.pathname) {
$(this).addClass("active");
} else {
$(this).removeClass("active");
}
})
})

I had soluve my questions just need to paste the js codes in my footer.html , and it works as my except . Maybe there are best way to solve this problem ...
the js codes like this :
<script>
$(function () {
$(".navbar-nav .NavHead").each(function () {
if ($("a",this).attr("href") === location.pathname) {
$(this).addClass("active");
return true;
} else {
$(this).removeClass("active");
}
});
});
</script>

Related

How can I active link in Navigation Bar when I click any item located in that bar?

I have a problem about changing the class attribute as active when I click any selected item in the navigation bar.
I wrote this js code which is shown below to implement this process but it didn't work.
Here is my HeaderPartialView part.
.... css files
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Here is my _Layout.cshtml part.
....
#{
Html.RenderAction("HeaderPartial", "Home");
}
#{
Html.RenderAction("NavbarPartial", "Home");
}
....
#{
Html.RenderAction("JSFilesPartial", "Home");
}
Here is my JSFilesPartial files.
<script src="~/Content/SiteLayout/assets/js/navigation-bar.js"></script>
Here is my navigation-bar.js file.
$(document).ready(function () {
var current = location.pathname;
$('.navigation-bar li a').each(function(){
var $this = $(this);
if($this.attr('href').indexOf(current) !== -1){
$this.addClass('active');
}
})
});
Here is NavbarPartial file.
<nav id="navbar" class="navbar">
<ul class="navigation-bar">
<li><a class="active" href="/Home/Index">Home</a></li>
<li>About Us</li>
<li>Projects</li>
</ul>
<i class="bi bi-list mobile-nav-toggle"></i>
</nav><!-- .navbar -->
How can I fix the issue?
$(document).ready(() => {
$(".somClass li a").on('click', (e) => {
$(".somClass li a").removeClass('active');
$(e.target).addClass('active');
});
});
.active {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="somClass">
<li><a class="active" href="#">link 1</a></li>
<li>link 2</li>
<li>link 3</li>
</ul>
Since you have active class as prop of anchor element you should try with .navigation-bar li a instead
You're adding the active class on the li element. It should be adding to the a element instead. The following should work:
<script type="text/javascript">
$(document).ready(function () {
$(".navigation-bar li a").on("click", function () {
$(".navigation-bar li a").removeClass("active");
$(this).addClass("active");
});
});
</script>
But it will fail because you're switching pages, and the javascript is reloaded every time you click in a anchor element.
I think this is what you're looking for:
var current = location.pathname;
$('.navigation-bar li a').each(function(){
var $this = $(this);
if($this.attr('href').indexOf(current) !== -1){
$this.addClass('active');
}
})
It basically searches with navigation element is currently active, adding the active class on the a element.
Here is the solution:
Navbar
<nav id="navbar" class="navbar">
<ul class="navigation-bar">
<li>AnaSayfa</li>
<li>Hakkımızda</li>
<li>Hizmetler</li>
<li>Portfolio</li>
<li>Blog</li>
<li>Biz Kimiz</li>
<li>Bize Ulaşın</li>
</ul>
<i class="bi bi-list mobile-nav-toggle"></i>
</nav><!-- .navbar -->
Js file
$(document).ready(function () {
var current = location.pathname;
$('.navigation-bar li a').each(function () {
var $this = $(this);
if($this.attr('href').indexOf(current) !== -1){
$this.addClass('active');
}
})
});

Toggle nav not opening

The website is http://109.74.0.128/~app/assistanstv/assistanstv/www.assistans.tv/tv.html
HTML:
<nav class="menu">
<ul class="active">
<li class="current-item">Home</li>
<li>Barnasisstans</li>
<li>Intervjuer</li>
<li>Juridik</li>
<li>LSS2020</li>
<li>Resor</li>
<li>Utbildning</li>
</ul>
<a class="toggle-nav" href="#">☰</a>
</nav>
jquery
jQuery(document).ready(function() {
jQuery('.toggle-nav').click(function(e) {
jQuery(this).toggleClass('active');
jQuery('.menu ul').toggleClass('active');
e.preventDefault();
});
});
the css code is too long, i cant get it work anyway. This drive me soon crazy. Whats wrong?!
Edit: Problem solved. The problem was
it was a / in the end. I solved it by deleted the last /
I think you want this:
$(document).ready(function() {
$('.toggle-nav').click(function(e) {
$('.toggle-nav').removeClass('active')
$(this).toggleClass('active');
$('.menu ul').toggleClass('active');
e.preventDefault();
});
});
CSS
.active {
background:tomato;
}
this class just a sample for showing toggling of class
updatelink of your code

Links not working while applying slideToggle

while applying slideToggle function the links are not working. below is the link for my demo site.
http://codezigns.com/teyseer_laboratory/htm/toggle.html
my script is
$(".nav li > a").click(function(e) {
$(this).parent().siblings().find('ul').slideUp(500);
$(this).next('ul').stop().slideToggle(300);
return false;
});
and also include
$(".trigger").click(function(e) {
e.preventDefault();
$(".main-nav > ul").slideToggle(300);
});
Link is applied in parent item "Tutorial" and child item "Photoshop".
Remove return false; from your a click event. It is preventing redirection.
This is happening because you are returning false on a click event, you should exclude the links from returning false, you should add a class to the real links and exclude them of your function:
HTML
<nav class="nav">
<ul>
<li>Home</li>
<li>Tutorials
<ul>
<li><a class="reallink" href="https://www.google.co.in/">Photoshop</a></li>
<li>Illustrator</li>
<li>Web Design</li>
</ul>
</li>
<li>Articles</li>
<li>Inspiration</li>
</ul>
</nav>
JS:
$(".nav li > a:not(.reallink)").click(function(e) {
$(this).parent().siblings().find('ul').slideUp(500);
$(this).next('ul').stop().slideToggle(300);
return false;
});
Hope it helps
The problem is you are returning false for each a click. Try like following. Hope this will help you.
$(".nav li > a").click(function (e) {
if(this.href.indexOf('#') > -1) {
$(this).parent().siblings().find('ul').slideUp(500);
$(this).next('ul').stop().slideToggle(300);
return false;
}
});

how to set active class to nav menu from twitter bootstrap

I'm new to the twitter bootstrap. Using there navigation menus . I'm trying to set active class to selected menu.
my menu is -
<div class="nav-collapse">
<ul class="nav">
<li id="home" class="active">Home</li>
<li>Project</li>
<li>Customer</li>
<li>Staff</li>
<li id="broker">Broker</li>
<li>Sale</li>
</ul>
</div>
I tried following thing after googling on this that i have to set active class on each page from menu like as--
<script>
$(document).ready(function () {
$('#home').addClass('active');
});
</script>
but problem for above is that i set home menu selected by default. Then it always get selected. Is there any other way to do this ? , or which i can generalize and keep my js in layout file itself?
After executing application my menu looks -
after clicking on other menu item i get following result-
And i added following scripts on Index view and Broker view ---
<script>
$(document).ready(function () {
$('#home').addClass('active');
});
</script>
<script>
$(document).ready(function () {
$('#broker').addClass('active');
});
</script>
respectively.
You can use this JavaScript\jQuery code:
// Sets active link in Bootstrap menu
// Add this code in a central place used\shared by all pages
// like your _Layout.cshtml in ASP.NET MVC for example
$('a[href="' + this.location.pathname + '"]').parents('li,ul').addClass('active');
It'll set the <a>'s parent <li> and the <li>'s parent <ul> as active.
A simple solution that works!
Original source:
Bootstrap add active class to li
it is a workaround. try
<div class="nav-collapse">
<ul class="nav">
<li id="home" class="active">Home</li>
<li>Project</li>
<li>Customer</li>
<li>Staff</li>
<li id="demo">Broker</li>
<li id='sale'>Sale</li>
</ul>
</div>
and on each page js add
$(document).ready(function () {
$(".nav li").removeClass("active");//this will remove the active class from
//previously active menu item
$('#home').addClass('active');
//for demo
//$('#demo').addClass('active');
//for sale
//$('#sale').addClass('active');
});
I had the same problem... solved it by adding the code shown below to the Into "$(document).ready" part of my "functions.js" file which is included in every page footer. It's pretty simple. It gets the full current URL of the displayed page and compares it to the full anchor href URL. If they are the same, set anchor (li) parent as active. And do this only if anchor href value is not "#", then the bootstrap will solve it.
$(document).ready(function () {
$(function(){
var current_page_URL = location.href;
$( "a" ).each(function() {
if ($(this).attr("href") !== "#") {
var target_URL = $(this).prop("href");
if (target_URL == current_page_URL) {
$('nav a').parents('li, ul').removeClass('active');
$(this).parent('li').addClass('active');
return false;
}
}
}); }); });
For single-page sites where the menu items simply jump down to other sections of the page, this simple solution works for me:
$('.nav li').on('click', function(){
$('.nav li').removeClass('active');
$(this).addClass('active');
});
You could add a diffrent class onto the BODY tag on each page e.g. on the homepage you could have this:
<body class="nav-1-on">
Then this css:
.nav-1-on .nav-1 a, .nav-2-on .nav-2 a, .nav-3-on .nav-3 a, .nav-4-on .nav-4 a {
// set your styles here
}
The NAV element:
<ul>
<li class="nav-1">Home</li>
<li class="nav-2">Services</li>
<li class="nav-3">About</li>
<li class="nav-4">Contact</li>
</ul>
#
Alternatively you could place a class on the BODY on each page and then grab that via jQuery and add the .active class to the correct nav item based on that tag.
<div class="nav-collapse">
<ul class="nav">
<li class="home">Home</li>
<li class="Project">Project</li>
<li class="Customer">Customer</li>
<li class="Staff">Staff</li>
<li class="Broker">Broker</li>
<li class="Sale">Sale</li>
</ul>
</div>
then for each page you add this:
//home
$(document).ready(function () {
$('.home').addClass('active');
});
//Project page
$(document).ready(function () {
$('.Project').addClass('active');
});
//Customer page
$(document).ready(function () {
$('.Customer').addClass('active');
});
//staff page
$(document).ready(function () {
$('.Staff').addClass('active');
});
<div class="nav-collapse">
<ul class="nav">
<li class="home">Home</li>
<li class="Project">Project</li>
<li class="Customer">Customer</li>
<li class="Staff">Staff</li>
<li class="Broker">Broker</li>
<li class="Sale">Sale</li>
</ul>
</div>
$('ul.nav>li.home>a').click(); // first. same to all the other options changing the li class name
For single page sites, the following is what I used. It not only sets the active element based on what's been clicked but it also checks for a hash value within the URL location on initial page load.
$(document).ready(function () {
var removeActive = function() {
$( "nav a" ).parents( "li, ul" ).removeClass("active");
};
$( ".nav li" ).click(function() {
removeActive();
$(this).addClass( "active" );
});
removeActive();
$( "a[href='" + location.hash + "']" ).parent( "li" ).addClass( "active" );
});
For those using Codeigniter, add this below your sidebar menu,
<script>
$(document).ready(function () {
$(".nav li").removeClass("active");
var currentUrl = "<?php echo current_url(); ?>";
$('a[href="' + currentUrl + '"]').parents('li,ul').addClass('active');
});
</script>
(function (window) {
bs3Utils = {}
bs3Utils.nav = {
activeTab: function (tabId) {
/// <summary>
/// 设置需要展现的tab
/// </summary>
/// <param name="tabId"></param>
$('.nav-tabs a[href="#' + tabId + '"]').tab('show');
}
}
window.bs3Utils = bs3Utils;
})(window);
example:
var _actvieTab = _type == '0' ? 'portlet_tab2_1' : 'portlet_tab2_2';
bs3Utils.nav.activeTab(_actvieTab);
<ul class="nav nav-tabs">
<li class="active">
箱-单灯节点
</li>
<li>
箱-灯组节点
</li>
</ul>
$( ".nav li" ).click(function() {
$('.nav li').removeClass('active');
$(this).addClass('active');
});
check this out.
I am using Flask Bootstrap.
My solution is a little bit simpler because my template already receives the option or choice as a parameter from Flask.
var choice = document.getElementById("{{ item_kind }}");
choice.className += "active";
First line, js code gets the element. So, you should identify each of the elements with a id. I'll show an example below.
Second line, you add the class active.
You can see html ids below.
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a id="speed" href="{{ url_for('list_gold_per_item',item_kind='speed',level='2') }}">
<h2>Speed</h2>
</a>
</li>
<li>
<a id="life" href="{{ url_for('list_gold_per_item',item_kind='life',level='3') }}">
<h2>Life</h2>
</a>
</li>
</ul>
</div>
I just added a custom class to the ul section named target-active
<ul class="nav navbar-nav target-active">
<li>HOME</li>
<li>FIND A TRUCK</li>
<li>OUR SERVICES</li>
<li>ABOUT US</li>
</ul>
If each li tags click get a new page from different place or same place, no need to add jquery removeClass function.
Add simple one line jquery code to each page to get your desired result
1st link page
$(function(){
$(".target-active").find("[href='/']").parent().addClass("active");
});
2nd link page
$(function(){
$(".target-active").find("[href=find-truck]").parent().addClass("active");
});
3rd link page
$(function(){
$(".target-active").find("[href=our-service]").parent().addClass("active");
});
4th link page
$(function(){
$(".target-active").find("[href=about-us]").parent().addClass("active");
});

How to show a list on mouse click using jquery?

With the following code:
<html>
<head>
<script type="text/javascript" src="jquery-1.7.js"></script>
<script language="JavaScript">
$(document).ready(function(){
$('#cssdropdown li.headlink').hover(
function() { $('ul', this).css('display', 'block'); },
function() { $('ul', this).css('display', 'none'); });
});
</script>
</head>
<body>
<ul id="cssdropdown">
<li class="headlink">
Search Engines
<ul>
<li>Google</li>
<li>Yahoo</li>
<li>Live Search</li>
</ul>
</li>
<li class="headlink">
Shopping
<ul>
<li>Amazon</li>
<li>eBay</li>
<li>CraigsList</li>
</ul>
</li>
</ul>
</body>
</html>
I can show a list on mouse over.
I want to show the lists on mouse click instead.
For instance, if I click on Search Engines, the Google, Yahoo and Live Search list will happear.
Try this:
$("UL UL").css("display", "none");
$(".title").click(function(e) {
e.preventDefault();
$(this).next("UL").toggle();
});
I've added a class of title to each of your clickable items so that the code can be reused.
Fiddle here
Just give an id to the <a> tag and make an event for that. like this: $('#search_engines').click(function () { });
This should give the behaviour you want, any open list will be hidden and the appropriate list opened:
$('li.headlink ul').hide();
$('li.headlink > a').click(function(e) {
e.preventDefault();
$('li.headlink ul').hide();
$(this).next().show();
});
or using the toggle approach so you can close all lists:
$('li.headlink ul').hide();
$('li.headlink > a').click(function(e) {
e.preventDefault();
var thisList = $(this).next();
thisList .toggle();
$('li.headlink ul').not(thisList).hide();
});
Here is a JSFiddle showing the second approach working

Categories