Maintaining active navigation state in JQuery/JavaScript after clicking a link: tips and tricks

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;

});

Answer №1

One way to achieve this is by using localStorage. Here's an example:

//Check for session variables.
$(document).ready(function() {

    // Set parameters object for initialization
    let paramsObj = {page:'current-page-name',link:location.href};
    
    // Initialize pageSession object to store the current page
    localStorage.setItem('pageSession', JSON.stringify(paramsObj));
    
    // Retrieve updated page session settings
    let pageStorage = localStorage.getItem('pageSession') != undefined ? JSON.parse(localStorage.getItem('pageSession')) : paramsObj;
   
    // make selected nav option active.
    let activeTab = '#' + pageStorage.page;
    $(activeTab).addClass('active');

    //Set link location for page refresh/reload
    $(document).on('click','nav a',function(e){

      e.preventDefault();
      //Set 'page' and 'link' variables based on nav values. 
      let page = JSON.parse(localStorage.getItem('pageSession')).page;
      let link = JSON.parse(localStorage.getItem('pageSession')).link;

      // Set 'page' and 'link' session variables based on nav values.
      localStorage.setItem('pageSession', JSON.stringify({page:$(this).attr('id'), link:$(this).attr('href')}));

      // Update classes.
      $('nav .active').removeClass('active'); 
      $(this).addClass('active');

      // Link to nav href.
      window.location = $(this).attr('href');

  });


 });
nav a.active {
     border-bottom: 3px solid #d10f0f;
 }
<nav>
    <a href="javascript:;" id="home" >Home</a>
    <span class="nav_divide"></span>
    <a href="javascript:;" id="about" >About</a>
    <span class="nav_divide"></span>
    <a href="javascript:;" id="work" >Work</a>
    <span class="nav_divide"></span>
    <a href="javascript:;" id="mission" >Mission</a>
    <span class="nav_divide"></span>
    <a href="javascript:;" id="contact" >Contact</a>
</nav>

There are multiple ways to accomplish this. The code has been updated to initialize pageSession on every page, resolving the issue with JSON.parse(...).

Give it a try here at jsfiddle. It should work now!

I hope this information proves helpful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble converting response.data to a string in ReactJS

import React, { Component } from 'react' import TaskOneServices from '../services/TaskOneServices' import circle from '../assets/icons/dry-clean.png' import tick from '../assets/icons/check-mark.png' async function ...

Customize checkbox and label using jQuery

I have a scenario where I have multiple checkboxes and corresponding labels. When the answer is correct, I want to change the background color of the selected checkbox and label. <input type="checkbox" id="a" class="check-with-label" /> <label fo ...

Is there a way to personalize the appearance of Static File in nextjs?

Is there a way to customize the display of static files, particularly images? For instance, when accessing a static file on a website like this: Currently, it just shows a basic img element. Is it possible to dynamically add additional elements to that d ...

Guide to connecting a different HTML page to a thumbnail image using jQuery

let newColumnBlock = $('<div class="col-md-2">'); let newImagePoster = $('<img>'); let newSelectButton = $('<a href="secondPage.html"><button class="selectButton"></button></a>'); let movie ...

Is it possible to securely share login details on the internet?

I'm currently brainstorming different ways to securely display FTP, database, and hosting information for website projects on my project management site. One potential solution I'm considering is encrypting the passwords and developing an applica ...

Tips for customizing the event target appearance in Angular 2?

After following the steps outlined in this particular blog post (section 3, event binding), I successfully added an event listener to my component class. I can confirm that it responds when the mouse enters and exits. <p class="title" (mouseenter)="unf ...

Is it possible to modify the labels on CKEditor's toolbar elements?

Initializing CKEditor in the following manner: function init() { $( ".ckeditor" ).ckeditor( { format_tags: 'h3;p', toolbar: [ [ "Source", "-", "Bold", "Italic" ], [ "Link", "Unlink" ], [ "Blockquote", "F ...

I am unable to apply CSS to style my <div> element

I've run into a snag with my coding project, specifically when attempting to style my div. Here is the code I have so far: All CSS rules are applying correctly except for the .chat rule. Can someone help me figure out what I'm doing wrong? var ...

Breaking up an array into smaller chunks with a slight twist

Here's a straightforward question. I have an array, like this: let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], maxChunkLength = 3; I am looking to divide this array into multiple arrays as follows: [[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9], [9, ...

The {shade} of the code has been modified within brackets

Ever encountered your code's colors abruptly changing to red and green in the middle of an HTML page? My editor is Brackets, and while it doesn't pose any issues, it's really bothersome and makes the code difficult to read: Take a look at t ...

Issue with Material UI scrollable tabs failing to render properly in Internet Explorer

Currently, we are integrating Material UI into our tab control for our React Web UI. Everything is functioning smoothly in Chrome, but when we attempted to test it in IE, the page failed to load and presented the error below: Unhandled promise rejection ...

Only add table heading if there is available space, but refrain from doing so if it will disrupt the layout

My current challenge involves a table where I have successfully used white-space nowrap to prevent the heading text from wrapping. The issue arises when viewing the layout on smaller screen widths, as this nowrap setting causes the table to expand beyond ...

Can you provide a succinct explanation of what constitutes a well-defined "landing page"?

Could someone provide a clear and concise explanation of what exactly constitutes a landing page and how it should be utilized? I'm struggling to grasp the concept. Where is the optimal placement for a landing page on a website? Is it best placed o ...

What is the best way to activate materialise pop-up menus in a React application?

Looking to enhance my React app by adding a NavBar with dropdown functionality. Here's the code snippet: <ul id="dropdown1" className="dropdown-content"> <li><NavLink to="/create">Create lesson ...

What causes CSS animations to suddenly halt?

Recently, I've been delving into the world of CSS animations and experimenting with some examples. Below is a snippet of code where two event handlers are set up for elements, both manipulating the animation property of the same element. Initially, th ...

Issues with JQuery OnClick Function Detected

I am struggling with an issue related to the scripts in the <head> section of my website: <script src="scripts/jquery-1.11.0.min.js" type="text/javascript"></script> <script> $('#submit').click(function() { $('#submi ...

A dynamic jQuery plugin that replicates the smooth page sliding animation found in iPhone apps

Currently, I am in search of a jQuery plugin that has the capability to navigate users to different pages on a website with a sleek sliding animation, similar to what we see in some widely used iPhone apps. Despite my best efforts to create this functional ...

Automatically send users to the login page upon page load if they are not authenticated using Nuxt and Firebase

I'm currently facing an issue with setting up navigation guards in my Nuxt application. The goal is to redirect users to the login screen if they are not authenticated using Firebase Authentication. While the router middleware successfully redirects u ...

Navigating through React-router with multiple child elements

Creating one of my routes requires the presence of two children in order to function properly. The main application page, where I set up all the routes, might look something like this: <Route path="/logs" component={Logs}> <Route path="/logs ...

Adjusting the size of an object as the page dimensions change

I am looking to dynamically resize an element whenever the document resizes. For example, if a draggable div is moved and causes the document to scroll, I want to adjust the size of another element using $("#page").css('height','120%'); ...