DizzyDan Posted October 18, 2013 Share Posted October 18, 2013 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 More sharing options...
davej Posted October 18, 2013 Share Posted October 18, 2013 This is an Ajax-driven page? Why not simply apply the class when you click on the link? Link to comment Share on other sites More sharing options...
justsomeguy Posted October 18, 2013 Share Posted October 18, 2013 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 More sharing options...
lovewebdesign Posted October 24, 2013 Share Posted October 24, 2013 Did you just put the active as the same color as normal? Link to comment Share on other sites More sharing options...
dsonesuk Posted October 24, 2013 Share Posted October 24, 2013 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 More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now