I have a list of links that link to sections within the page using anchor tags. I’m trying to grab the current class name initially when the user loads the page and add the class of “active” to the list item. So for instance, if a user goes to http://www.mydomain.com/#about-section, the navigation will remove the existing ‘active’ class and then add the class to the current link.
<nav id="primary">
<ul>
<li class="active"><a href="#intro-section">Home</a></li>
<li><a href="#work-section">Work</a></li>
<li><a href="#about-section">About</a></li>
<li><a href="#contact-section">Contact</a></li>
</ul>
</nav>
How would I go about changing the class depending on which section is in view using jQuery?
Well you’d just bind “click” handlers to the
<a>tags.If your nav structure is deeper or more complicated or whatever, you’d need to use more specific selectors.
edit — if you want to have this happen upon page load, you’d have to do something in a “ready” handler:
edited — the code above originally added “active” to the
<a>instead of its parent<li>– thanks to @scessor for the correction.