Show last active div on refresh JS - javascript

I have a fairly basic navigation tab on a single-page website that shows/hides divs. However, when I refresh the page, it goes back to the landing "page" div instead of staying on the current tab. I am using the following JS to switch between tabs and I would like to keep using this method if possible:
var links = document.getElementById('navs').getElementsByTagName('a');
for(var i = 0, link; link = links[i]; i++) {
link.onclick = showContent;
// Hide content divs by default
var contentdiv = getContentDiv(link)
if (contentdiv == null){
continue;
}
contentdiv.style.display = 'none';
}
// Show the first content div
if(links.length > 0) showContent.apply(links[0]);
var current;
function showContent() {
// hide old content
if(current) current.style.display = 'none';
current = getContentDiv(this);
if(!current) return true;
current.style.display = 'inline-block';
return true;
}
function getContentDiv(link) {
var linkTo = link.getAttribute('href');
console.log(linkTo);
// Make sure the link is meant to go to a div
if(linkTo.substring(0, 2) != '#!') return;
linkTo = linkTo.substring(2);
return document.getElementById(linkTo);
}
I know it refreshes to the landing div because of
if(links.length > 0) showContent.apply(links[0]);
However, I was hoping to use this method and store the link iteration number in a variable called current_link and then be able to call if(links.length > 0) showContent.apply(links[current_link]); or even if(links.length > 0) showContent.apply(current_link);
I have tried a couple ways, but it ends up just saving either the first or last tab in the navigation bar. Also the page refreshes to the default div, but the url stays the same. EX. The URL is http://example.com/#!tab1 even though the page is displaying http://example.com/#!home
This is the html:
<nav class="navbar navbar-fixed-top" id= "navs" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<div class="navbar-brand">
<a id="logo" href="#!home"><img id="logo-pic" src="images/name.png" alt="" width="50%" height="auto"></a>
</div>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="navbar" id="navbar-collapse-1">
<ul class="nav navbar-right navbar-nav">
<li class="dropdown">
tab1
</li>
<li>
<a class="dropdown-toggle" data-toggle="dropdown" href="#">tab2</a>
<ul class="dropdown-menu dropdown-menu-right pull-center">
<li>tab21</li>
<li>tab22</li>
</ul>
</li>
<li>
<a class="dropdown-toggle" data-toggle="dropdown" href="#">tab3</a>
<ul class="dropdown-menu dropdown-menu-right pull-center">
<li>resume</li>
<li>tab31</li>
<li>tab32</li>
</ul>
</li>
<li>
tab4
</li>
<li>
tab5
</li>
</ul>
</div>
</div>
<!-- /.container -->
</nav>

The best way to persist page state is to leverage the url history.
E.g. when the user clicks on a tab, instead of just doing the navigation:
Create a hashchange event handler
window.onhashchange = () => { ... };
or:
window.addEventListener('hashchange', () => ...);
So you might do something like:
const navigate = () => open_tab(location.hash.substr(1)); // get rid of the '#'
window.addEventListener('hashchange', navigate);
You also want to navigate when the page loads:
navigate();
Now, when the user clicks a tab, or whatever, change the hash of the page location:
location.hash = "tab1";
This is a little extra work but the benefits are huge:
Refreshing the page works as expected
If the user bookmarks the page, they bookmark the state of the UI
Forward and backward navigation now work as expected.

Related

Is it possible to add links to bootstrap 4 nav-pills tab-panel from a different page?

I have a service page that using bootstrap 4's pills .nav-pills navigation (this is not the main navigation navbar), which is working very well. My challenge is that i want to be able to click on a link on the home page that should open the targeted tab-panel on the service page. Haven't been able to find a way for almost a week now. How can i achieve this?
Service.html
<div class="nav flex-column nav-pills col-md-3" id="v-pills-tab" role="tablist" aria-orientation="vertical">
<ul class="list-group list-unstyled">
<li class="nav-item">
<a class="nav-link list-group-item" id="v-pills-manpower-tab" data-toggle="pill" href="#v-pills-manpower" role="tab" aria-controls="v-pills-manpower" aria-selected="false">Manpower Supply</a>
</li>
</ul>
</div>
<div class="tab-content col-md-8" id="v-pills-tabContent">
<div class="tab-pane fade" id="v-pills-manpower" role="tabpanel" aria-labelledby="v-pills-manpower-tab">
<h5>Man Power Supply</h5>
</div>
Home.html
<a href="services.html#v-pills-manpower" data-toggle="tab" >
My code in home.html doesn't work but that's one of my many attempts.
On the home page, configure data attributes to help. I've added data-tab-name to the anchor and it defines the desired, selected tab for the service page.
When the page loads, it re-configures the onclick of the link so that the tab name can be stored in localStorage before redirecting the user to the service page.
Home.html
<a href="services.html" data-tab-name="v-pills-manpower" data-toggle="tab" >
<script type="text/javascript">
window.onload = function() {
document.querySelectorAll('[data-toggle="tab"]').forEach(function(item, index){
item.addEventListener('click', function(e){
e.preventDefault();
localStorage.selectedTabName = item.getAttribute('data-tab-name');
window.location.href = item.href;
});
});
};
</script>
When the service page loads, the javascript looks for the saved tab name in localStorage, identifies that tab and then makes it the active tab by applying the "active" class to the appropriate element.
Service.html
<script type="text/javascript">
window.onload = function() {
document.querySelectorAll('.nav-link').forEach(function(item, index){
var isActive = (item.className.indexOf('active')>-1);
if (item.id==localStorage.selectedTabName) {
if (!isActive) {
item.className += ' active';
}
item.setAttribute('aria-selected', 'true');
} else {
item.setAttribute('aria-selected', 'false');
if (isActive) {
item.className = item.className.replace('active', '');
}
}
});
};
</script>

Automatically selecting tab upon redirect

I am running a ruby on rails website and it currently supports javascript an jquery. I am using htmlslim, scss, and bootstrap.
I am wondering it if is possible to have a button or link that sends a user to another page, then automatically clicks on a tab on that page.
For instance I have a page with the following compiled html:
...
<div class="row">
<ul class="nav nav-tabs profile-tabs" id="userTabs">
<li class="active" id="userItems" role="presentation">
<a data-toggle="tab" href="#items" role="tab">
<span class="key">Items</span>
<span class="value">13</span>
</a>
</li>
<li role="presentation">
<a class="stand-card-activate" data-toggle="tab" href="#people" role="tab">
<span class="key">People</span>
<span class="value">3</span>
</a>
</li>
</ul>
</div>
...
This is a row with 2 tabs and the Items tab is the tab that is by default selected when the user visits the page.
Is there some way to make a button that can link to this page and have the People tab automatically selected?
Here is the same code in slim:
...
.row
ul#userTabs.nav.nav-tabs.profile-tabs
li#userItems.active[role="presentation"]
a(href="#items" role="tab" data-toggle="tab")
span.key Items
span.value = #user.items.count
li(role="presentation")
a.stand-card-activate(href="#people" role="tab" data-toggle="tab")
span.key people
span.value = #people_count
...
EDIT 2:
Code so far:
slim:
a.back-to-user-people-btn.pull-left(href=www.yourpage.com/#people) Back to People
JS:
var hash= window.location.hash;
if(hash.length > 0 ) {
$('a[role="tab"]').parent().removeClass('active');//remove the default active tab
$('a[href="'+hash+'"]').parent().addClass('active');
}
This jquery allows it to have the correct tab name highlighted and "active" but the contents of the items tab is still the content that the user sees.
EDIT 3: Show tab contents slim code
.tab-content
#items.tab-pane.fade.active.in.col-md-12(arialabelledby="items" role="tabpanel")
.card-container = render partial: 'partials/item', collection: #user[:items], as: :user_item, locals: {user: #user}
#people.tab-pane.fade.active.in.col-md-12(arialabelledby="people" role="tabpanel")
Try something like this
a link should look like : www.yourpage.com/#tabhrefid
When the page is loaded it will take the hash from the url and add the class active to the tab witch has the link with the same href
$(function(){
var hash= window.location.hash;
if(hash.length > 0 ) {
$('a[role="tab"]').parent().removeClass('active');//remove the default active tab
$('a[href="'+hash+'"]').parent().addClass('active');
$('.tab-pane').removeClass('active');
$(hash).addClass('active');
}
});

Link to Jquery Tab does not work

I am working on a L5 project and i am using a Jquery tab for one of its pages. I have a little menu for reaching tab contents without clicking just tabs.
<div id="aracislem" class="panel-collapse collapse">
<div class="panel-body">
<ul>
<li>Araç Arama </li>
<li>Araç Kayıt </li>
<li>İstatistik </li>
<li>Araç Takibi </li>
</ul>
</div>
</div>
Any my tab is
<script type="text/javascript">
$(document).ready(function () {
$('#tab-container').tabs({
active: $.cookie('activetab'),
activate: function (event, ui) {
$.cookie('activetab', ui.newTab.index(), {
expires: 10
});
}
});
});
</script>
<div id="tab-container" class='tab-container'>
<ul>
<li class='tab'>Araç Arama</li>
<li class='tab'>Araç Kayıt</li>
<li class='tab'>İstatistik</li>
<li class='tab'>Araç Takip</li>
</ul>
<div class='panel-container'>
<div id="aracaramatab">
Araç Arama
</div>
<div id="arackayittab">
Araç Kayıt
</div>
<div id="istatistiktab">
İstatistik
</div>
<div id="aractakiptab">
Araç Takip
</div>
</div>
</div>
When i clik to menu links i cant reach to necessary tab, link changes in the browser but does not redirect to tab also when i click to tabs, content changes but links do not change. Anybody knows what am i doing wrong ?
Check this DEMO : http://jsfiddle.net/yeyene/mktgnp3e/1/
Your problem is when you click link and after going to link (it will redirect a different page?), want to active the tab, right?
So get the url first, then get the hash, then do the active tab step.
JQUERY
$(document).ready(function () {
$("#tab-container").tabs({});
// for testing purpose
var url = "http://localhost/pages/aracislemler#arackayittab";
// use this script for getting url
//var url = window.location.href;
var hash = url.substring(url.indexOf('#'));
// trigger click to tab with url hash name
$('#tab-container a[href='+hash+']').trigger('click');
});
*Use the line var url = window.location.href; for your app, then take out the current url getting test variable.

Make all direct parent list entries selected in mmenu

I'm working on a project where I'm about to use the jQuery plugin mmenu (http://mmenu.frebsite.nl/).
I already had to do some customisations to fit my needs but I don't know what to do with my current issue. In mmenu, when i click on an list entry I will be navigated to the given href and the clicked item becomes active by mmenus css class ".mm-selected". So far so good.
Now I want to additionally mark the parent list item (and thats parent, and so on until menu root) as selected. This should be so when the user goes one level up in the menu he should be able to see in which category he currently is.
Below is an example of the menus html structure after mmenu was applied. This shows the code for a menu with 4 main pages (index, page1, page2 and page3) and 3 subpages (2.1, 2.2, 2.3).
<nav id="nav" class="mm-menu mm-horizontal mm-offcanvas mm-hasheader mm-current mm-opened">
<ul class="mm-list mm-panel mm-opened mm-current" id="mm-0">
<li class="mm-selected">
Index
</li>
<li>
Page 1
</li>
<li>
<a class="mm-subopen mm-fullsubopen" href="#mm-1"></a>
<span>Page 2</span>
</li>
<li>
Page 3
</li>
</ul>
<ul class="mm-list mm-panel mm-highest" id="mm-1">
<li class="mm-subtitle">
<a class="mm-subclose" href="#mm-0">Page 2</a>
</li>
<li>
Page 2.1
</li>
<li>
Page 2.2
</li>
<li>
Page 2-3
</li>
</ul>
</nav>
It would be great if you had some idea where and how I could achive such functionality.
So, for the moment I did some jQuery hacking. This seems to work for my case mentioned above. It should also work for deeper menus as it's using recursion. If there's a better way to achieve this, please let me know.
var nav = $("#nav");
nav.find("li > a:not(.mm-subopen)").click(function () {
nav.find("li.active").removeClass("active");
selectParentEntry($(this));
});
var selectParentEntry = function (a) {
var li = a.parent(),
ul = li.parent(),
back = ul.find("li > a.mm-subclose").first(),
cID = "#" + ul.attr("id"),
pID = back.length ? back.attr("href") : null;
li.addClass("active");
if (pID != null) {
var subOpen = nav.find("ul" + pID + " > li > a.mm-subopen").filter(function () {
var self = $(this);
if (self.attr("href") === cID) return self;
}).first();
if (subOpen) selectParentEntry(subOpen);
}
};

Bootstrap navbar Active State not working

I have bootstrap v3.
I use the class="active" on mynavbar and it does not switch when I press menu items. I know how to do this with jQuery and build a click function but I'm thinking this functionality should be included in bootstrap? So maybe it is a JavaScript issue?
Here is my header with my js/css/bootstrap files I have included:
<!-- Bootstrap CSS -->
<link rel="stylesheet" href= "/bootstrap/css/bootstrap.css" />
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />
<link rel="stylesheet" href= "/stylesheets/styles.css" />
<!--jQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<!-- Bootstrap JS -->
<script src="/bootstrap/js/bootstrap.min.js"></script>
<script src="/bootstrap/js/bootstrap-collapse.js"></script>
<script src="/bootstrap/js/bootstrap-transition.js"></script>
Here is my navbar code:
<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbarCollapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/index.php">MyBrand</a>
</div>
<div class="collapse navbar-collapse navbarCollapse">
<ul class="nav navbar-nav navbar-right">
<li class="active">
Home
</li>
<li>
Links
</li>
<li>
About
</li>
<li>
Contact
</li>
<li>
Login
</li>
</ul>
</div>
</div>
</nav>
Am I setting this up right?
(On an unrelated note, but possible related? When the menu goes mobile, I click the menu button and it collapses. Pushing it again does not un-collapse it though. So this issue,. with the other, both signify wrong JavaScript setup perhaps?)
You have included the minified Bootstrap js file and collapse/transition plugins while the docs state that:
Both bootstrap.js and bootstrap.min.js contain all plugins in a single file.
Include only one.
and
For simple transition effects, include transition.js once alongside
the other JS files. If you're using the compiled (or minified)
bootstrap.js, there is no need to include this—it's already there.
So that could well be your problem for the minimize problem.
For the active class, you have to manage it yourself, but it's just a line or two.
Bootstrap 3:
$(".nav a").on("click", function(){
$(".nav").find(".active").removeClass("active");
$(this).parent().addClass("active");
});
Bootply: http://www.bootply.com/IsRfOyf0f9
Bootstrap 4:
$(".nav .nav-link").on("click", function(){
$(".nav").find(".active").removeClass("active");
$(this).addClass("active");
});
Here was my solution for switching active pages
$(document).ready(function() {
$('li.active').removeClass('active').removeAttr('aria-current');
$('a[href="' + location.pathname + '"]').closest('li').addClass('active').attr('aria-current', 'page');
});
This worked perfectly for me, because "window.location.pathname" also contains data before the real page name, e.g. directory/page.php. So the actual navbar link will only be set to active if the url contains this link.
$(document).ready(function() {
$.each($('#navbar').find('li'), function() {
$(this).toggleClass('active',
window.location.pathname.indexOf($(this).find('a').attr('href')) > -1);
});
});
With version 3.3.4 of bootstrap, on long html pages you can refer to sections of the pg. by class or id to manage the active navbar link with spy-scroll with the body element:
<body data-spy="scroll" data-target="spy-scroll-id">
The data-target will be a div with the id="spy-scroll-id"
<div id="spy-scroll-id" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li>About</li>
<li>SlideShow</li>
</ul>
</div>
This should activate links by clicking without any javascript functions needed and will also automatically activate each link as you scroll through the corresponding linked sections of the page which a js onclick() will not.
All you need to do is simply add data-toggle="tab" to your link inside bootstrap navbar like this:
<ul class="nav navbar-nav">
<li class="active"><a data-toggle="tab" href="#">Home</a></li>
<li><a data-toggle="tab" href="#">Test</a></li>
<li><a data-toggle="tab" href="#">Test2</a></li>
</ul>
If you don't use anchor links, you can use something like this:
$(document).ready(function () {
$.each($('#navbar').find('li'), function() {
$(this).toggleClass('active',
'/' + $(this).find('a').attr('href') == window.location.pathname);
});
});
With Bootstrap 4 you can use this:
$(document).ready(function() {
$(document).on('click', '.nav-item a', function (e) {
$(this).parent().addClass('active').siblings().removeClass('active');
});
});
This elegant solution did the trick for me. Any new ideas/suggestions are welcome.
$( document ).on( 'click', '.nav-list li', function ( e ) {
$( this ).addClass( 'active' ).siblings().removeClass( 'active' );
} );
You can use jQuery's "siblings()" method to keep only the accessed item active and its siblings inactive.
I use this. It's short, elegand and easy to understand.
$(document).ready(function() {
$('a[href$="' + location.pathname + '"]').addClass('active');
});
I've been struggling with this today, data-togle only worked if I'm on a single page application.
I'm not using ajax to load the content i'm actually making post request for other pages so the first js script was useless too. I solve it with this lines:
var active = window.location.pathname;
$(".nav a[href|='" + active + "']").parent().addClass("active");
Bootstrap 4: navbar Active State working, just use .navbar-nav .nav-link classes
$(function () {
// this will get the full URL at the address bar
var url = window.location.href;
// passes on every "a" tag
$(".navbar-nav .nav-link").each(function () {
// checks if its the same on the address bar
if (url == (this.href)) {
$(this).closest("li").addClass("active");
//for making parent of submenu active
$(this).closest("li").parent().parent().addClass("active");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-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" href="#">Other</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'm hope this will help to solve this problem.
var navlnks = document.querySelectorAll(".nav a");
Array.prototype.map.call(navlnks, function(item) {
item.addEventListener("click", function(e) {
var navlnks = document.querySelectorAll(".nav a");
Array.prototype.map.call(navlnks, function(item) {
if (item.parentNode.className == "active" || item.parentNode.className == "active open" ) {
item.parentNode.className = "";
}
});
e.currentTarget.parentNode.className = "active";
});
});
I had some pain with this, using a dynamically generated list items - WordPress Stack.
Added this and it worked:
$(document).ready(function () {
$(".current-menu-item").addClass("active");
});
Will do it on the fly.
I've been looking for a solution that i can use on bootstrap 4 navbars and other groups of links.
For one reason or another most solutions didn't work especially the ones that try to add 'active' to links onclick because of course once the link is clicked if it takes you to another page then the 'active' you added won't be there because the DOM has changed.
Many of the other solutions didn't work either because they often did not match the link or they matched more than one.
This elegant solution is fine for links that are different ie: about.php, index.php, etc...
$(function() {
$('nav a[href^="' + location.pathname.split("/")[2] + '"]').addClass('active');
});
However when it came to the same links with different query strings such as index.php?tag=a, index.php?tag=b, index.php?tag=c it would set all of them to active whichever was clicked as it's matching the pathname not the query as well.
So i tried this code which matched the pathname and the query string and it worked on all the links with query strings but when a link like index.php was clicked it would set the similar query string links active as well. This is because my function is returning an empty string if there is no query string in the link, again just matching the pathname.
$(function() {
$('nav a[href^="' + location.pathname.split("/")[2] + returnQueryString(location.href.split("?")[1]) + '"]').addClass('active');
});
/** returns a query string if there, else an empty string */
function returnQueryString (element) {
if (element === undefined)
return "";
else
return '?' + element;
}
So in the end i abandoned this route and kept it simple and wrote this.
$('.navbar a').each(function(index, element) {
//console.log(index+'-'+element.href);
//console.log(location.href);
/** look at each href in the navbar
* if it matches the location.href then set active*/
if (element.href === location.href){
//console.log("---------MATCH ON "+index+" --------");
$(element).addClass('active');
}
});
It works on all links with or without query strings because element.href and location.href both return the full path. For other menus etc you can simply change the parent class selector (navbar) for another ie:
$('.footer a').each(function(index, element)...
One last thing which also seems important and that is the js & css library's you are using however that's another post perhaps.
I hope this helps and contributes.
Vanilla JS solution for Bootstrap 5
document.addEventListener("DOMContentLoaded", function () {
// make all currently active items inactive
// (you can delete this block if you know that there are no active items when loading the page)
document.querySelectorAll("a.nav-link.active").forEach(li => {
li.classList.remove("active");
li.attributes.removeNamedItem("aria-current");
});
// find the link to the current page and make it active
document.querySelectorAll(`a[href="${location.pathname}"].nav-link`).forEach(a => {
a.classList.add("active");
a.setAttribute("aria-current", "page");
});
});
Class "active" is not managed out of the box with bootstrap. In your case since you're using PHP you can see:
How add class='active' to html menu with php
to assist you with a method of mostly automating it.
For bootstrap mobile menu un-collapse after clicking a item you can use this
$("ul.nav.navbar-nav li a").click(function() {
$(".navbar-collapse").removeClass("in");
});
I m using bootstrap bare theme, here is the sample navbar code. Note the class name of the element -> .nav - as this is referred in java script.
/ Collect the nav links, forms, and other content for toggling
#bs-example-navbar-collapse-1.collapse.navbar-collapse
%ul.nav.navbar-nav
%li
%a{:href => "/demo/one"} Page One
%li
%a{:href => "/demo/two"} Page Two
%li
%a{:href => "/demo/three"} Page Three
in the view page (or partial) add this :javascript,
this needs to be executed every time page loads.
haml view snippet ->
- content_for :javascript do
:javascript
$(function () {
$.each($('.nav').find('li'), function() {
$(this).toggleClass('active',
$(this).find('a').attr('href') == window.location.pathname);
});
});
In the javascript debugger make sure you have value of 'href' attribute matches with window.location.pathname. This is slightly different than the solution by #Zitrax which helped me fixing my issue.
For AngularJS, you can use ng-class with a function like this:
HTML ->
<nav class="navbar navbar-default" ng-controller="NavCtrl as vm">
<div class="container">
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav" >
<li ng-class="vm.Helper.UpdateTabActive('Home')"><a href="#" ng-click>Home</a></li>
<li ng-class="vm.Helper.UpdateTabActive('About')">About</li>
<li ng-class="vm.Helper.UpdateTabActive('Contact')">Contact</li>
</ul>
</div>
</nav>
And controller
app.controller('NavCtrl', ['$scope', function($scope) {
var vm = this;
vm.Helper = {
UpdateTabActive: function(sTab){
return window.location.hash && window.location.hash.toLowerCase() == ("#/" + sTab).toLowerCase() ? 'active' : '';
}
}
}]);
If you are using $location, then there won't be hash. So you can extract the required string from URL using $location
Following will not work in all cases -->
Using a scope variable like following will work only when clicked, but if the transition is done using $state.transitionTo or window.location or manually updating the URL, the Tab value will not be updated
<ul class="nav navbar-nav" ng-init="Tab='Home'">
<li ng-class="Tab == 'Home' ? 'active' : ''">Home</li>
<li ng-class="Tab == 'About' ? 'active' : ''">About</li>
</ul>
Add this JavaScript on your main js file.
$(".navbar a").on("click", function(){
$(".navbar").find(".active").removeClass("active");
$(this).parent().addClass("active");
});
I had to go a step forward because my file names were not the same as my nav bar titles. i.e. my first nav bar link was HOME but the file name is index..
So just grab the pathname and match it.
Obviously this is a crude example and could be more efficient but it is highly custom need.
var loc_path = location.pathname;
$('li.active').removeClass('active');
if(loc_path.includes('index')){
$('li :eq(0)').addClass('active');
}else if(loc_path.includes('blog')){
$('li :eq(2)').addClass('active');
}else if(loc_path.includes('news')){
$('li :eq(3)').addClass('active');
}else if(loc_path.includes('house')){
$('li :eq(4)').addClass('active');
}
Bootstrap 4 solution that worked for me:
$(document).ready(function() {
//You can name this function anything you like
function activePage(){
//When user lands on your website location.pathname is equal to "/" and in
//that case it will add "active" class to all links
//Therefore we are going to remove first character "/" from the pathname
var currentPage = location.pathname;
var slicedCurrentPage = currentPage.slice(1);
//This will add active class to link for current page
$('.nav-link').removeClass('active');
$('a[href*="' + location.pathname + '"]').closest('li').addClass('active');
//This will add active class to link for index page when user lands on your website
if (location.pathname == "/") {
$('a[href*="index"]').closest('li').addClass('active');
}
}
//Invoke function
activePage();
});
This will only work if href contains location.pathname!
If you are testing your site on your own pc (using wamp, xampp, lamp, etc...) and your site is located in some subfolder then your path is actually "/somefolder/something.php", so don't get confused.
I would suggest if you are unsure to use following code so you can make sure what is the correct location.pathname:
$(document).ready(function() {
alert(location.pathname);
});
the next answer is for those who have a multi-level menu:
var url = window.location.href;
var els = document.querySelectorAll(".dropdown-menu a");
for (var i = 0, l = els.length; i < l; i++) {
var el = els[i];
if (el.href === url) {
el.classList.add("active");
var parent = el.closest(".main-nav"); // add this class for the top level "li" to get easy the parent
parent.classList.add("active");
}
}
As someone who doesn't know javascript, here's a PHP method that works for me and is easy to understand. My whole navbar is in a PHP function that is in a file of common components I include from my pages. So for example in my 'index.php' page I have...
`
<?php
$calling_file = basename(__FILE__);
include 'my_common_includes.php'; // Going to use my navbar function "my_navbar"
my_navbar($calling_file); // Call the navbar function
?>
Then in the 'my_common_includes.php' I have...
<?php
function my_navbar($calling_file)
{
// All your usual nabvbar code here up to the menu items
if ($calling_file=="index.php") { echo '<li class="nav-item active">'; } else { echo '<li class="nav-item">'; }
echo '<a class="nav-link" href="index.php">Home</a>
</li>';
if ($calling_file=="about.php") { echo '<li class="nav-item active">'; } else { echo '<li class="nav-item">'; }
echo '<a class="nav-link" href="about.php">About</a>
</li>';
if ($calling_file=="galleries.php") { echo '<li class="nav-item active">'; } else { echo '<li class="nav-item">'; }
echo '<a class="nav-link" href="galleries.php">Galleries</a>
</li>';
// etc for the rest of the menu items and closing out the navbar
}
?>
Bootstrap 4 requires you to target the li item for active classes. In order to do that you have to find the parent of the a. The 'hitbox' of the a is as big as the li but due to bubbeling of event in JS it will give you back the a event. So you have to manually add it to its parent.
//set active navigation after click
$(".nav-link").on("click", (event) => {
$(".navbar-nav").find(".active").removeClass('active');
$(event.target).parent().addClass('active');
});
I tried about first 5 solutions and different variations of them, but they didn't work for me.
Finally I got it working with these two functions.
$(document).on('click', '.nav-link', function () {
$(".nav-item").find(".active").removeClass("active");
})
$(document).ready(function() {
$('a[href="' + location.pathname + '"]').closest('.nav-item').addClass('active');
});
when use header.php for every page for the navbar code, the jquery does not work, the active is applied and then removed, a simple solution, is as follows
on every page set variable
<?php $pageName = "index"; ?> on Index page and similarly
<?php $pageName = "contact"; ?> on Contact us page
then call the header.php (ie the nav code is in header.php)
<?php include('header.php'); >
in the header.php ensure that each nav-link is as follows
<a class="nav-link <?php if ($page_name == 'index') {echo "active";} ?> href="index.php">Home</a>
<a class="nav-link <?php if ($page_name == 'contact') {echo "active";} ?> href="contact.php">Contact Us</a>
hope this helps cause i have spent days to get the jquery to work but failed,
if someone would kindly explain what exactly is the issue when the header.php is included and then page loads... why the jquery fails to add the active class to the nav-link..??
For Bootstrap 5 I use the folowing to keep the dropdown items active after navigating to a url.
<li class="nav-item dropdown text-center ">
<a class="nav-link dropdown-toggle dropdown-toggle-split" href="#" id="navbarDropdown1" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Clienten
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown1">
<li><h6 class="dropdown-header">Iedereen</h6></li>
<li><a class="dropdown-item " aria-current="page" href="/submap/IndexClients.php">Overzicht</a></li>
<li><hr class="dropdown-divider"></li>
<li><h6 class="dropdown-header">Persoonlijk</h6></li>
<li><a class="dropdown-item" aria-current="page" href="/submap/IndexClientsP.php">Overzicht (<?= $usernamesession ?>)</a></li>
</ul>
</li>
<script>
$(document).ready(function() {
$('a.active').removeClass('active');
var active = window.location.pathname;
$('a[href="' + active + '"]').closest('.dropdown-item').addClass('active');
});
</script>
Bootstrap 5.1
This is already implemented in bootstrap, and explained neatly in the documentation under the scrollspy section. Link to documentation
Steps to fix active state toggle:
set position:relative on your body element
add id="navbar" to your navbar section.
include this in your js file, or inside in the html:
var scrollSpy = new bootstrap.ScrollSpy(document.body, {
target: '#navbar'
})
With bootstrap 4 I missed from the documentation that I needed to also add
$('#myList a').on('click', function (e) {
e.preventDefault()
$(this).tab('show')
})
https://getbootstrap.com/docs/4.0/components/list-group/

Categories