I'm trying to add an active
class (i.e. class="active"
) to the appropriate menu list item based upon the page it is on once the page loads. Below is my menu as it stands right now. I've tried every snippet of code I could find in this regard and nothing works. So, can someone please explain simply where and how to add in javascript to define this task?
<ul id="nav">
<li id="navhome"><a href="home.aspx">Home</a></li>
<li id="navmanage"><a href="manageIS.aspx">Manage</a></li>
<li id="navdocso"><a href="docs.aspx">Documents</a></li>
<li id="navadmin"><a href="admin.aspx">Admin Panel</a></li>
<li id="navpast"><a href="past.aspx">View Past</a></li>
</ul>
Here is an example of the javascript that I'm putting in my head tag in my site master. What am I doing wrong?
$(document).ready(function () {
$(function () {
$('li a').click(function (e) {
e.preventDefault();
$('a').removeClass('active');
$(this).addClass('active');
});
});
});
To make the clicked tab active in the navigation bar, the <li> corresponding to the clicked href in index. html introduces the css of 'active' class and removes the 'active' class from the previous <li> on click.
The :active selector is used to select and style the active link. A link becomes active when you click on it. Tip: The :active selector can be used on all elements, not only links.
The reason this isn't working is because the javascript is executing, then the page is reloading which nullifies the 'active' class. What you probably want to do is something like:
$(function(){ var current = location.pathname; $('#nav li a').each(function(){ var $this = $(this); // if the current path is like this link, make it active if($this.attr('href').indexOf(current) !== -1){ $this.addClass('active'); } }) })
There are some cases in which this won't work (multiple similarly pointed links), but I think this could work for you.
jQuery(function($) {
var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
$('ul a').each(function() {
if (this.href === path) {
$(this).addClass('active');
}
});
});
.active, a.active {
color: red;
}
a {
color: #337ab7;
text-decoration: none;
}
li{
list-style:none;
}
<h3>Add Active Navigation Class to Menu Item</h3>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about/">About</a></li>
</ul>
<h2><a href="http://www.sweet-web-design.com/examples/active-item/active-class.html">Live Demo</a></h2>
With VANILLA plain JavaScript
(function () {
var current = location.pathname.split('/')[1];
if (current === "") return;
var menuItems = document.querySelectorAll('.menu-item a');
for (var i = 0, len = menuItems.length; i < len; i++) {
if (menuItems[i].getAttribute("href").indexOf(current) !== -1) {
menuItems[i].className += "is-active";
}
}
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With