Function to add class to page user is currently on - javascript

similar questions have already been answered, but I'm having trouble implementing them in my own code:
Add active class to current page navigation link
Dynamically change CSS of link based on current page
jQuery active link current page
Basically, I'm trying to figure out how to add a class to an anchor tag if the anchor tag matches the current page the user is on. I have three html pages - Index, About, and Contact. They all have the same navbar.
-----------------------------------Index.html----------------------------------------------------------------------
<nav class="navbar navbar-inverse navbar-fixed-top"><!-- navbar begings -->
<div class="container">
<div class="navbar-header">
<button aria-expanded="false" class="navbar-toggle collapsed" data-target="#bs-nav-demo" data-toggle="collapse" type="button">
<span class="sr-only">Toggle navigation</span>
</button>
<a class="navbar-brand" href="http://vetamuse.com">Manuel Stoilov</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li><a class="navAnchor" href="about.html">About |</a></li>
<li><a class="navAnchor" href="contact.html">Contact |</a></li>
</ul>
</div>
</div>
</nav>
-----------------------------------About.html----------------------------------------------------------------------
<nav class="navbar navbar-inverse navbar-fixed-top"><!-- navbar begings -->
<div class="container">
<div class="navbar-header">
<button aria-expanded="false" class="navbar-toggle collapsed" data-target="#bs-nav-demo" data-toggle="collapse" type="button">
<span class="sr-only">Toggle navigation</span>
</button>
<a class="navbar-brand" href="http://vetamuse.com">Manuel Stoilov</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li><a class="navAnchor" href="about.html">About |</a></li>
<li><a class="navAnchor" href="contact.html">Contact |</a></li>
</ul>
</div>
</div>
</nav>
-----------------------------------Contact.html----------------------------------------------------------------------
<nav class="navbar navbar-inverse navbar-fixed-top"><!-- navbar begings -->
<div class="container">
<div class="navbar-header">
<button aria-expanded="false" class="navbar-toggle collapsed" data-target="#bs-nav-demo" data-toggle="collapse" type="button">
<span class="sr-only">Toggle navigation</span>
</button>
<a class="navbar-brand" href="http://vetamuse.com">Manuel Stoilov</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li><a class="navAnchor" href="about.html">About |</a></li>
<li><a class="navAnchor" href="contact.html">Contact |</a></li>
</ul>
</div>
</div>
</nav>
In my css, my .navAnchors are syled. I want to also add class .current to the anchor tag that matches the page the user is currently on.
----------------------------------index.css-----------------------------------
.navbar-collapse > .nav > li > a:link,
.navbar-collapse > .nav > li > a:visited
{
color: #95a1aa;
font-size: 15px;
}
.current {
color: pink;
}
I'm currently trying this function in JavaScript, but it's not working:
------------------------index.js-----------------------
var path = window.location.pathname.split("/").pop();
var link = $(".navAnchor");
window.setInterval(function(){
for(var i = 0; i < 2; i++) { //2 refers to the number of links on nav page (about and contact)
if(path === link.eq(i).attr('href')){
link.eq(i).addClass("current");
}
}
}, 5000);
The links for the pages are:
(index.html) https://preview.c9users.io/manistoi/vetamuse/vetamuse/v3/index.html?_c9_id=livepreview8&_c9_host=https://ide.c9.io
(about.html) https://preview.c9users.io/manistoi/vetamuse/vetamuse/v3/about.html
(contact.html) https://preview.c9users.io/manistoi/vetamuse/vetamuse/v3/contact.html
Any help or tips are appreciated!!
--------------------------------------EDIT---------------------------------------------
The following works for me (in my javascript tab)
$(document).ready(function(){
var path = window.location.pathname.split("/").pop();
$(".navAnchor").each(function(){
if($(this).attr('href') == path){
$(this).css("color", "black");
$(this).css("font-weight", "bold");
}
})
})

You want the current class to be on the li - not the a. Iterate over your navlink a's and check the href and if it matches your path variable - add the current class to the a's parent (the li). However - if you decide you want the Current class on the a - just ingnore the parent() in the code and it should work fine. Also - just noted that you have the pages titled with capital letters- but your hrefs are lowercase - eg: About.html vs about.html. These will need to be the same case.
$(document).ready(function(){
var path = window.location.pathname.split("/").pop();
$(".navAnchor").each(function(){
if($this).attr('href') == path){
$(this).parent().addClass('current');
}
})
})

Related

How to redirect active class to dropdown submenu?

I have created a navbar with dropdown. Navigating works quite well. And the "active" class can be transferred without problems, but not to the "li" elements of the dropdown. All active "li" are underlined with border-bottom. If I navigate to "li" element "dropdown" it will be underlined, but not the selected "li" item in dropdown. What am I doing wrong?
Here is my index.html
<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-
toggle="collapse" data-target="#collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<section class="layout">
<div class="branding">
<a href="/"><img src="images/header/app_fh_logo.png"
alt="App logo"></a>
</div><!--branding-->
</section><!--layout-->
</div><!--navbar-header-->
</div>
<div class="collapse navbar-collapse" id="collapse">
<ul class="nav navbar-nav navbar-right">
<li alt="standard"><a href="/"><span class="glyphicon glyphicon-
home"></span>Startseite</a>
</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<span class="glyphicon glyphicon-envelope"></span>Messenger<b class="caret">
</b></a>
<ul class="dropdown-menu">
<li><a href="/profile"><span class="glyphicon glyphicon-
user"></span>Konto</a></li>
<li><a href="/about"><span class="glyphicon glyphicon-
info-sign"></span>Über</a></li>
<li><a href="#"><span class="glyphicon glyphicon-log-
out"></span>Abmelden</a></li>
</ul>
</li>
</ul>
</div><!-- navbar collapse -->
</nav>
here is js
$(".nav a").filter(function () {
return this.href == location.href
}).parent().addClass("active").siblings().removeClass("active");
$("li").click(function () {
// remove classes from all
$("li").removeClass("active");
// add class to the one we clicked
$(this).addClass("active");
});
Thanks in advance.
$("li").click(function () {
$("li").each(function(index, ele) {
$(ele).removeClass("active");
});
$(this).addClass("active");
});
use jquery each function inside li click function to remove all active classes

Navbar menu not closing (With click on menu and li elements)

I have tried multiple solutions surrounding this issue which I have found on stack but I still can't seem to solve my particular issue. this is what I am working on http://dev.joneslewis.co.uk/. As you can see, in mobile view the hamburger menu doesn't collapse once opened whether I click on li element or the menu itself. As the site is based on anchors it's a real pain...
Here is the html I am currently working with and the Js...
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" rel="home" href="#">
<img class="img-responsive" style="max-width:35px; margin-top: -7px;"
src="#"/>
</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li><a data-toggle="collapse" data-target=".navbar-collapse" href="#about">About</a></li>
<li><a a data-toggle="collapse" data-target=".navbar-collapse" href="#contact">Contact</a></li>
</ul>
</div>
</div>
</nav>
Javascript...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://joneslewis.co.uk/bootstrap/jquery.js"></script>
<script src="http://joneslewis.co.uk/bootstrap/bootstrap.min.js"></script>
<script>
$(document).ready(function () {
$(".navbar-nav li a").click(function(event) {
$(".navbar-collapse collapse").collapse('hide');
});
});
</script>
It appears the selector is incorrect. I tried this and I was able to select the component and hide the menu.
$(".navbar-collapse.collapse").collapse('hide')

Bootstrap Menu Collapse Disappear

Hello all,
I am trying to make a navbar disappear after being clicked (It also has a sub menu dropdown). I tried using this (in fact it worked for a while but now does not). Any help would be appreciated, David
<script type="text/javascript">
<!--Make the menu collapse on option click in mobile mode-->
jQuery(document).ready(function () {
jQuery(".nav .dropdownmenu, .navbar-header .dropdownmenu").click(function(event) {
// check if window is small enough so dropdown is created
jQuery(".navbar-collapse").removeClass("in").addClass("collapse");
});
});
</script>
This is the dropdown menu
<!-- Fixed navbar -->
<nav class="navbar navbar-default navbar-fixed-top" >
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<img src = "images/logo.png" height="30px" style="margin-top: 10px; margin-left: 5px;">
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li class="dropdownmenu active">Home</li>
<li class="dropdownmenu">Sales</li>
<li class="dropdownmenu">Lettings</li>
<li class="dropdownmenu">Financial Services</li>
<li class="dropdown">
Branches <span class="caret"></span>
<ul class="dropdown-menu">
<li class="dropdownmenu" data-toggle="modal" data-target="#northwichModal"><a >Northwich</a></li>
<li class="dropdownmenu" data-toggle="modal" data-target="#middlewichModal">Middlewich</li>
<li class="dropdownmenu" data-toggle="modal" data-target="#winsfordModal">Winsford</li>
<li class="dropdownmenu" data-toggle="modal" data-target="#lettingsModal">Northwich Lettings</li>
</ul>
</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</nav>

Collapse NavBar only when user is X pixels down the page

Is it possible to make Bootstrap only collapse the nav bar when the user is X pixels down the page?
I know this can be done for Affixing the menu by using the data attribute data-offset-top. But using this same attribute on the collapse button or on the nav div doesn't achieve this.
<nav class="navbar">
<div class="container-fluid">
<div>
<a class="navbar-brand" href="/"><img src="img/logo.png" alt=""/></a>
</div>
<!-- Affix Navbar when 280px from top: This works -->
<div class="navbar-header pull-right" data-spy="affix" data-offset-top="280">
<!-- Collapse Navbar when 280px from top: Doesn't work -->
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-offset-top="280" data-target="#navbar-collapse">
<span class="sr-only">Toggle navigation</span>
</button>
<!-- The below should collapse only when the user is 280px or more from the top -->
<div class="collapse navbar-collapse" id="navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li class="active">
<a class="text-uppercase page-scroll" href="#call-to-action">home</a>
</li>
</ul>
</div>
</div>
</div>
</nav>
You could always do it yourself with jquery.
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = 150; // set to whatever you want it to be
if(y_scroll_pos >= scroll_pos_test) {
$('#navbar-collapse').collapse('hide');
} else {
$('#navbar-collapse').collapse('show');
}
});
Note: Builds on this answer
If you are using lodash/underscore, you could use throttle to make sure the function doesn't execute too often.

Bootstrap Navbar Collapse not closing on Click

I'm using Bootstrap an it's collapsed Navbar on a one-page website together with a simple scrolling script, so if I click on a single link the page scrolls down to anchor - works great. However the Navbar does not collapse when I click on a link which covers a lot of content on mobile devices - you first have to click on the toggle which is annoying. I found out that it should help to add the data-toggle and data-target attributes to the links, but it doesn't work at all - where is my mistake?
NAVIGATION:
<nav class="navbar navbar-default mainbar" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle hvr-bounce-to-bottom" data- toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a data-toggle="collapse" data-target=".navbar-collapse" href="#link1" class="navelement">Link 1</a></li>
<li><a data-toggle="collapse" data-target=".navbar-collapse" href="#link2" class="navelement">Link 2</a></li>
</ul>
</div>
</nav>
UPDATE:
It's a Javascript problem. My smooth-scroll script causes an issue:
var corp = $("html, body");
$(".navelement").click(function() {
var flag = $.attr(this, "href");
corp.animate({
scrollTop: $(schild).offset().top - 60
}, 1600, function() {
window.location.hash = flag;
});
return false;
});
It's a pretty simple script, but I have no clue what to do with it to make the navbar collapse.
Using the above example, what worked for me was to add data-toggle="collapse" data-target=".navbar-collapse" to the outer div
<div class="collapse navbar-collapse" id="my-navbar-collapse">
<div class="collapse navbar-collapse" id="my-navbar-collapse" toggle="collapse" data-target=".navbar-collapse">
The entire menu looks like this with the change:
<nav class="navbar navbar-expand-xl navbar-light bg-light">
<a class="navbar-brand" href="#">Main</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=".navbar-collapse" >
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" routerLink="/home">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item active">
<a class="nav-link" routerLink="/guitars">Guitars <span class="sr-only">(current)</span></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" routerLink="/nasa-image">NASA Image</a>
<a class="dropdown-item disabled" href="#">Another action</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item disabled" href="#">Something else here</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#">Disabled</a>
</li>
</ul>
</div>
</nav>
I know this is a bit late coming in however, even in Bootstrap 4.0.0-alpha.6; the navbar does NOT inherently close after a menu item selection. The docs at Bootsrap have gotten better - but there is NO clear-cut example on how to get the navbar to close after a new menu selection.
In your html file - you go to the target div for the collapse class - the div I'm sowing below came strait from the Bootstrap site - so nothing has changed on that note:
<div class="collapse navbar-collapse" id="navbarSupportedContent">
You use that id to monitor if the navbar is expanded (out of collapsed mode), then I added a click event to the a.nav-links in the navbar that re-collapses the navbar:
$("#navbarSupportedContent").on('show.bs.collapse', function() {
$('a.nav-link').click(function() {
$("#navbarSupportedContent").collapse('hide');
});
});
I would recommend following this a little bit closer to help you out.
http://getbootstrap.com/components/#navbar
Seems to be what you are basing it off of.
Mainly, when you look # that link, look at the first button line that you have and compare as that is your main drop down on the mobile version which takes up lots of screen real estate as you mentioned.
<nav class="navbar navbar-default mainbar" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle hvr-bounce-to-bottom collapsed" data-toggle="collapse" data-target="#my-navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="my-navbar-collapse">
<ul class="nav navbar-nav">
<li><a data-toggle="collapse" data-target=".navbar-collapse" href="#link1" class="navelement">Link 1</a></li>
<li><a data-toggle="collapse" data-target=".navbar-collapse" href="#link2" class="navelement">Link 2</a></li>
</ul>
</div>
</nav>
1) I changed this part data- toggle="collapse" to data-toggle="collapse". There was just an extra space on line 3.
2) I added an id to your drop down instead of a class to identify more particularly (may not matter) and also changed the name to "my-navbar-collapse" This change was made on lines 3 and 11. Also this previously means you were just using the same class twice on the same element which didn't make sense.
3) I added the class "collapsed" into your class on line 3 located after "hvr-bounce-to-bottom" Should allow it to be collapsed by default, and only show if it is opened by the user.
That should help fix it as it cleans it up. Also, do you have a drop down in your nav bar that needs to be brought back up when you toggle other than the main button you listed? Doesn't seem so as of yet, just asking to make sure it's clear.
This works for me:
$('.navbar-nav>li>a').on('click', function(){
$('.navbar-collapse').collapse('hide');
});
The only problem with the solution above and the JSFiddle (jsfiddle.net/camdixon/v2gosj5s) is that when you are not on a mobile device, and the menu is not collapsed, the menu items blink. E.g. they collapse in place and reopen in place.
To repeat: expand the window of the JSFiddle result so that the menu is not collapsed, then click on a navbar item.
I've sort of solved the issue in addition to the JSFiddle version by altering the collapse data api in bootstrap.js as follows:
//Bootstrap v3.3.4
//line 662:
Collapse.prototype.toggle = function () {
//Added code:
var mq = window.matchMedia('screen and (min-width: 768px)')
if (mq.matches) return
//End added code
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
I'd rather not hardcode the min-width, but don't yet know how I would access the media query values in the css (see #screen-sm-min in less).
$(document).ready(function () {
$(".navbar-nav li.trigger-collapse a").click(function(event) {
$(".navbar-collapse").collapse('hide');
});
});
This small jquery snippet works in this way:
If navbar is expanded, nothing happens, so no blink (normal bootstrap behavior).
If navbar is collapsed, after a click event, closes the navbar.
Works on bootstrap 4
$(".navbar a").click(function(event) {
// check if window is small enough so dropdown is created
var toggle = $(".navbar-toggler").is(":visible");
if (toggle) {
$(".navbar-collapse").collapse('hide');
}
});
.wrapper {
height: 400px;
}
#div1 {
background-color: #73683b;
}
#div2 {
background-color: #B0A084;
}
#div3 {
background-color: #E9E6FF;
}
#div4 {
background-color: #B3679B;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<div class="container px-0">
<nav class="navbar navbar-expand-lg navbar-dark bg-dark mx-0">
<a class="navbar-brand" href="#">Logo</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="#div1">Link 1</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#div2">Link 2</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#div3">Link 3</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#div4">Link 4</a>
</li>
</div>
</nav>
</div>
<div class="container wrapper d-flex flex-column justify-content-center" id="div1">
<p class="text-center">DIV 1</p>
</div>
<div class="container wrapper d-flex flex-column justify-content-center" id="div2">
<p class="text-center">DIV 2</p>
</div>
<div class="container wrapper d-flex flex-column justify-content-center" id="div3">
<p class="text-center">DIV 3</p>
</div>
<div class="container wrapper d-flex flex-column justify-content-center" id="div4">
<p class="text-center">DIV 4</p>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
You just need to add data-toggle and data-target in navbar code. Where class="collapse navbar-collapse navbar-collapse is used.
<div class="collapse navbar-collapse navbar-collapse" data-toggle="collapse" data-target="#navbar-collapse">
Home (current)
Guitars (current)
Dropdown
NASA Image
Another action
Something else here
Disabled
Just use span tag and add data-bs-toggle="collapse"` data-bs-target=".navbar-collapse" to each links. Finally this worked in my project.
<NavLink exact="true" className="nav-link" to="/">`<span data-bs-toggle="collapse"` data-bs-target=".navbar-collapse">Home</span></NavLink>
Just use span tag and add data-bs-toggle="collapse"` data-bs-target=".navbar-collapse" and place that span tag in anchor tag. below is the code
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<a class="navbar-brand" href="/">Navbar</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">
<li class="nav-item active">
<a class="nav-link" href="/"><span data-bs-target="#navbarSupportedContent" data-bs-toggle="collapse">Home</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#About"><span data-bs-target="#navbarSupportedContent" data-bs-toggle="collapse">About</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#Contact"><span data-bs-target="#navbarSupportedContent" data-bs-toggle="collapse">Contact</span></a>
</li>
</ul>
</div>
</div>
</nav>
In my case, the tabs had weird behavior and didn't close due to my vue :class bindings
<router-link class="nav-link text-light" :class="{active: checker}" to="/ideas">
This variant works
<router-link class="nav-link text-light" to="/ideas">

Categories

Resources