Jump to content

'Active' link highlights all link when on homepage


DizzyDan

Recommended Posts

This script works for the nav linking /about/, /services/. But when on the home page "/" all the button share the class 'active'.

 

HTML Nav

<nav id="cssmenu"><ul><li><a href='/'>Home</a></li><li><a href='/about-us/'>About</a></li><li><a href='/services/'>Services</a></li><li><a href='/contact/'>Contact</a></li></ul></nav>

Script

$(function() {  $('nav a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');});

 

Link to comment
Share on other sites

It looks like you're telling it that when the attribute starts with a slash to apply active, so obviously that's going to apply to every element. You might need to use an if statement to make a special case for the home page.

Link to comment
Share on other sites

its because as mentioned the search for slash will always found in all links, so it applies active class to all, unless you remove a single slash from being processed by the filter, and add active class when it is just a single slash.

location.pathname !='/' ? $('nav a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active') : $('nav a[href="/"]').addClass('active');
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...