Set Active State on Navigation Dynamically

Set active state on navigation dynamically

you could try something along the lines of

<li class="cemenu<?php echo ($_SERVER['PHP_SELF'] == '/about' ? ' active' : '');?>"><a href="<?php echo $base_url;?>/about">About</a></li>

How to dynamically change (add) the active state class to a navigation link

You need this:

var i = document.location.href.lastIndexOf("/");
var currentPHP = document.location.href.substr(i+1);
$("ul#main-menu li a").removeClass('active');
$("ul#main-menu li a[href^='"+currentPHP+"']").addClass('active');

How to set a NavLink to active conditionally on dynamic links

I took Drew Reese's suggestions and expanded on them to fit my needs.

I made it so the My Profile link is active if isProfileRoute and currentUsersProfile is met.

isActive={() => isProfileRoute && currentUsersProfile}

currentUsersProfile is on the AuthContext.

const AuthContext = createContext({
authorized: false,
profile: null,
currentUsersProfile: null,
setAuthorized: () => {},
setProfile: () => {},
setCurrentUsersProfile: () => {},

The currentUsersProfile is set in Profile to true when the current profile belongs to the current logged in user.:

  useEffect(() => {
if (profile?.name === currentUser().name) {
} else {
}, [profile]);

I create an array of all the routes:

const Routes = (
<Route path="/shop">
<Shop />
<Route path={"/pro"}>
<Profile />
<Route path={["/:profile_name", "/my_profile"]}>
<Profile />
const array = => child.props.path);
// outputs: ['/shop', '/pro', ["/:profile_name", "/my_profile"]]

In Nav I use this array to check to see if the current route the user is on is a the profile route (ex: '/dash123', '/somename', or the fixed route '/my_profile') using useMatchRoute

function Nav() {
const { currentUsersProfile } = useContext(AuthContext);
const allNonProfileRoutes = array.slice(0, -1);
let nonProfileRoute = useRouteMatch([...allNonProfileRoutes, { path: "/" }]);

const isProfileRoute = !nonProfileRoute.isExact;


Setting active class for menu items dynamically in laravel

Instead of defining a $currentPage variable in the layout files, you could use the

request()->is() method:

<li class="nav-item {{ request()->is('blog') ? 'active' : ''}}">
<a class="nav-link " href="{{ url('blog') }}">{{ __('sentence.Blog') }}</a>

The is() method essentially takes the current url path for the request and uses Str::is() to check against the pattern you've passed in.

This way you only having to check if the current URL matches the link URL and you don't have to define an extra piece of data somewhere else in your application.

Dynamically adding active class to a dynamically built nav menu line item using JavaSCript

The main reason it isn't working for you is that the elements don't exist in the document yet when you try to add the listeners.

There are two ways to fix this. One would be to add a listener to each <li> as you create them and before inserting them into the DOM. But the simpler solution is to use event delegation and attach one listener to the <ul> element and handle the event.targets.

You have a number of syntax errors, but below is a working edit of your snippet.

To control the classes assigned to an element you need to use the classList property of the element and its provided methods to add(), remove() or toggle() a class.

const navBar = document.querySelector('.navbar__list');
const navElements = document.querySelectorAll('section');

navBar.addEventListener('click', function (event) {

navElements.forEach(function (section) {
const navlistElement = `<li class='menu__link ${section.className}' data-link=${}><a href="#${}">${section.dataset.nav}</li>`
navBar.insertAdjacentHTML('beforeend', navlistElement)
.active {
background-color: tomato;
<nav class="navbar__menu">
<!-- Navigation starts as empty UL that will be populated with JS -->
<ul class="navbar__list"></ul>

<section id="section1" data-nav="Section 1" class="your-active-class">
<div class="landing__container">
<h2>Section 1</h2>
<p>Lorem ipsum dolor sit amet</p>
<section id="section2" data-nav="Section 2" class="your-active-class">
<div class="landing__container">
<h2>Section 2</h2>
<p>Lorem ipsum dolor sit amet</p>

complex active state navigation on single page website

You mean scrollspy? Check here

// Cache selectors
var lastId,
topMenu = $("#top-menu"),
topMenuHeight = topMenu.outerHeight()+15,
// All list items
menuItems = topMenu.find("a"),
// Anchors corresponding to menu items
scrollItems ={
var item = $($(this).attr("href"));
if (item.length) { return item; }

// Bind click handler to menu items
// so we can get a fancy scroll animation{
var href = $(this).attr("href"),
offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight+1;
$('html, body').stop().animate({
scrollTop: offsetTop
}, 300);

// Bind to scroll
// Get container scroll position
var fromTop = $(this).scrollTop()+topMenuHeight;

// Get id of current scroll item
var cur ={
if ($(this).offset().top < fromTop)
return this;
// Get the id of the current element
cur = cur[cur.length-1];
var id = cur && cur.length ? cur[0].id : "";

if (lastId !== id) {
lastId = id;
// Set/remove active class

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:

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){

There are some cases in which this won't work (multiple similarly pointed links), but I think this could work for you.

bootstrap dynamic navigation active class

Try this:

$("#nav li a").on("click", function(e){

$("#nav li").removeClass("active"); //Remove any previously "active" li
$("#home, #about, #contact").hide(); //Hide all "pages"
$($(this).prop("href")).show(); //Show only the current target
$(this).closest("li").addClass("active"); //Set click li as active

Related Topics

Leave a reply