How to add active class to nav link ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How to add active class to nav link ?

I want to use active class to denote current page is active : I have following folder structure hader file containing nav bar: header.php Lets say i have home.php admin.php ... etc. inside home.php i used require_once('header.php'); to include nav bar and same to each and every others page. So whenever i clicked the any nav item that active class must be appiled. I inserted JS code below and it works fine if i links goes no where but whenever i added the actual link for another page it lasts for few seconds and gone. So how to solve it. It isn't working because each time new page is loaded so it won't know the previous state to new page. So to make it working what should i do ? I haven't learned localstorage of js will it helps ? (If you haven't understand please check the post inserted with this question) JS code link: https://code.sololearn.com/WLkSKi4c1Lp9/?ref=app Post with full story: https://www.sololearn.com/post/721177/?ref=app

31st Oct 2020, 3:50 PM
Kuber Acharya
Kuber Acharya - avatar
2 Answers
+ 2
I'll suggest a different approach but to do exactly what you're asking, you should take a parameter with your code to print the common nav bar indicating which item to set 'active' on. If all your menu items are similar, you could put them in an array, loop through echoing them out, and add class="active" to only the matched item. The approach your question asks for isn't the cleanest, in my opinion. The cleanest approach I've had for this type of problem is actually to give every page a unique class on the body element, a different unique class on each nav item, and handle whatever styling you want for this "active" class through CSS selectors. For example, <li><a class="nav-home" href="/">Home</a></li> <li><a rel="nofollow" class="nav-profile" href="/profile">Profile</a></li> <li><a class="nav-faq" href="/faq">FAQ</a></li> <li><a class="nav-contact" href="/contact">Contact</a></li> and in CSS: .nav-home-page a.nav-home, .nav-profile a.nav-profile, .nav-faq a.nav-faq, .nav-contact a.nav-contact { color: #000; box-shadow: 0 0 4px #bbb inset; } The body for the home page could be something like body class="nav-home-page" which would make the a.nav-home element show as active. To a degree, my suggestion here is to basically solve the problem in CSS instead of PHP. Moving the solution isn't necessarily making it simpler but CSS isn't a programming language so the more you can solve with it, the simpler things generally get. Also, you might want to CSS select other elements uniquely to each page anyway.
1st Nov 2020, 6:31 PM
Josh Greig
Josh Greig - avatar
0
Josh Greig Thank you for your suggestion :)
5th Nov 2020, 4:38 AM
Kuber Acharya
Kuber Acharya - avatar