While many resources discuss adding the active class to a nav link using jquery, there is less information on maintaining the active state after the nav link has been clicked.
After experimenting with code from various sources, I have attempted to set session variables onclick in order to preserve the active state through navigation and reloading. However, my current approach does not seem to be effective.
What I have tried so far is not producing the desired results.
This method appears functional, but may not align with modern best practices.
HMTL:
<nav>
<a href="about.xhtml" id="about" >About</a>
<span class="nav_divide"></span>
<a href="work.xhtml" id="work" >Work</a>
<span class="nav_divide"></span>
<a href="mission.xhtml" id="mission" >Mission</a>
<span class="nav_divide"></span>
<a href="contact.xhtml" id="contact" >Contact</a>
</nav>
CSS:
nav a.active {
border-bottom: 3px solid #d10f0f;
}
Script:
//Check for session variables.
$(document).ready(function() {
//If 'page' session is defined
if (window.sessionStorage.pageSession) {
// make selected nav option active.
var activeTab = '#' + window.sessionStorage.pageSession;
$(activeTab).addClass('active');
} else {
// If pageSession is not defined, you're at home
window.sessionStorage.pageSession = ('page', 'home');
}
//Set link location for page refresh/reload
});
// Place or remove nav active state.
$(document).on('click','nav a',function(){
//Set 'page' and 'link' variables based on nav values.
var page = this.id;
var link = this.href;
// Set 'page' and 'link' session variables based on nav values.
var window.sessionStorage.pageSession = ('page', page);
var window.sessionStorage.linkSession = ('link', link);
// Update classes.
$('nav .active').removeClass('active');
$(this).addClass('active');
// Link to nav ahref.
window.location = sessionStorage.linkSession;
});