Add Active Navigation Class Based on Url

Add Active Navigation Class Based on URL

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.

Need help adding and removing .active class based on page URL using JS

Target only the .navbar-links a then loop over each one, in the loop do 2 things:

  • Check if current hash or path equals the links href attribute.
  • Add an event handler to the link to set the class, and before setting it, loop over the others to remove the current (not needed if you're not using a hash).

const menuItem = document.querySelectorAll('.navbar-links a');

menuItem.forEach(el => {
// current
if (el.getAttribute('href') === (location.hash || '#home')) {
el.classList.add("active")
}

// handle click
el.addEventListener("click", e => {
// remove others
menuItem.forEach(el => el.classList.remove("active"))
// set active
e.target.classList.add("active")
})
})
ul li a {
color: black;
background-color: silver;
}

ul li a.active {
color: white;
background-color: black;
}
<nav class="navbar">
<div class="navbar-links">
<ul>
<li><a href="#home">HOME</a></li>
<li><a href="#about">ABOUT</a></li>
<li><a href="#location">LOCATION</a></li>
</ul>
</div>
</nav>

Add Active Navigation Class Based On Url for similar url

Try this

if( new RegExp(location.pathname + "$").test( $this.attr('href') ) ) {
$this.addClass('active');
}

Tested with:

new RegExp('\/blog$').test('/blogAds'); // returns false
new RegExp('\/blog$').test('/blog'); // returns true

Reference

JQuery - Add active class based on URL but also different following sub paths

This will work

I converted my simpler script to jQuery to stay consistent with your code

const getPath = url => {
const path = new URL(url).pathname
const parts = path.split("/");
return parts.length < 3 || !parts.includes("tag") ? parts[1] : parts[3]
};

const path = getPath("https://yourserver.com/insight"); // getPath(location.href)

$("#nav a").each(function() {
const lnkPath = getPath($(this).prop("href"));
$(this).toggleClass("active", path === lnkPath)
})
.active {
color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="nav">
<a class="topic-link" href="/insight/page/1">All</a>
<a class="topic-link" href="/insight/tag/technology">Technology</a>
<a class="topic-link" href="/insight/tag/support">Support</a>
</div>

Active navigation class based on current URL problem

For home page add extra class 'default' in list like.

<li class="first default"><a href="/">Home</a></li>

jquery code.

 jQuery(function($){
var current = location.pathname;
console.log(current);
//remove the active class from list item.
$('.nav ul li a').removeClass('active');

if(current != '/'){
$('.nav ul li a').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if(current.indexOf($this.attr('href')) !== -1 && $this.attr('href') != '/'){
$this.addClass('active');
}
})
}else{
console.log('home');
$('.default a').addClass('active');
}
})

how to add class 'active' to nav item whose href is in the location.pathname

The following should theoretically work:

// Compute the closest (2-part) base path from the current location
var basePath = '/' + window.location.pathname.split('/', 3).filter(Boolean).join('/') + '/';

// Add `active` class to the corresponding link if any
$('#nav-item a[href="' + basePath + '"]').addClass('active');

The first line basically takes the first 2 parts of the pathName, so:

  • if the URL is /glossd/, it yields /glossd/,
  • if the URL is /glossd/reviews/, it yields /glossd/reviews/,
  • if the URL is /glossd/reviews/something/, it still yields /glossd/reviews/.


Related Topics



Leave a reply



Submit