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

Issue with if statement when checking element.checked

Hey everyone, I'm currently working on a calculator app and running into an issue. I have set up 3 radio buttons and I would like to check them using an 'if statement' in my JS file. However, the problem is that the 'main' element ...

What is the reason for the error that Express-handlebars is showing, stating that the engine

I recently added express-handlebars to my project and attempted the following setup: const express = require("express"); const exphbs = require('express-handlebars'); const app = express(); app.engine('.hbs', engine({defaultL ...

Make a quick call to the next function within the error handling module for a

Currently, I am facing an issue while trying to call the next function within the error handler of my node + express js application. In each controller, I have a middleware known as render which is invoked by calling next, and I wish to achieve the same f ...

Steps to enable the submit button in angular

Here's the code snippet: SampleComponent.html <nz-radio-group formControlName="radiostatus" [(ngModel)]="radioValue" (ngModelChange)="onChangeStatus($event)"> <label nz-radio nzValue="passed">Passed</label> <label nz-rad ...

What could be the reason for the malfunction of this AngularJS data binding feature?

I am trying to create an angularjs filter that outputs HTML, similar to what is discussed in the link, but I am encountering issues. In my HTML code, I have: <ul> <li ng-repeat="book in books | filter:query"> {{book.title}} ...

Looking to incorporate content from an external website onto my own site

I have experimented with various types of HTML tags such as iframe, embed, and object to display external websites. Some of them load successfully, while others do not. After researching my issue on Google, I discovered that "For security reasons, some si ...

What is the best way to create a function that will return a Promise within an Express Route?

I am working with a business level database module named "db_location" that utilizes the node-fetch module to retrieve data from a remote server through REST API. **db_location.js** DB LOGIC const p_conf = require('../parse_config'); const db_ ...

Is it possible to enable CSS margins to collapse across a fieldset boundary in any way?

One interesting CSS behavior is that adjacent vertical margins typically collapse into one another. In other words, the space between elements will be equal to the larger margin instead of the sum of both margins. Interestingly, fieldset elements do not f ...

Using 'require' within a nested directive that relies on the parent directive in AngularJS

Implementing a sub directive to be utilized in multiple directives is my current challenge. These parent directives share a common controller that has useful methods for updating scope variables within these directives: (potentially changing controllers ...

Show on Screen as Label Text

I am looking to change the display format from a popup box to a label text. How can I achieve this using JQuery? JQuery <script type="text/javascript> function ShowCurrentTime() { PageMethods.GetCurrentTime(document.getElementById("<%=txtUserNam ...

Exploring AngularJS: the power of directives and the art of dependency

According to Angular documentation, the recommended way to add a dependency is by following these steps: Source //inject directives and services. var app = angular.module('fileUpload', ['ngFileUpload']); app.controller('MyCtrl&ap ...

Methods for organizing an array of objects by a specific key in JavaScript, but in the case of duplicate values, the objects can be sorted by a different

I'm struggling to sort an array of objects by two different keys. I need to first sort the array by price, and if there are multiple items with the same price, they should then be sorted by time. Here's what my array looks like: var myArr = [ {&q ...

Is there a maximum size limit for the Fabric.js Path Array?

Has anyone tried plotting a line graph using Fabric.js and encountered issues with the fabric.Path? I've noticed that it stops drawing after 8 segments even though I have attempted different methods like loops and individually coding each segment. co ...

css - targeting the last child element using a type selector

I'm attempting to target the final child element of type <div> within the container "#myDiv" <div id="myDiv"> <div> <img> <div> <div>text</div> ...

The custom styles in Material-Table are taking precedence over all other styling, including Material UI styles, and causing icons to not

I recently started using the Material-Table component for a project I'm working on, and it's been great for managing tables with features like adding, editing, deleting, and searching rows. However, I've run into a few issues that I need hel ...

A guide on parsing a stringified HTML and connecting it to the DOM along with its attributes using Angular

Looking for a solution: "<div style="text-align: center;"><b style="color: rgb(0, 0, 0); font-family: "Open Sans", Arial, sans-serif; text-align: justify;">Lorem ipsum dolor sit amet, consectetur adipiscing e ...

Unlinked from the main content, the Angular2 Material2 sidenav stands on its

I am in the process of implementing the material2 sidenav component. My goal is to have a standalone, full-height sidebar that smoothly slides in and out without any interference with the rest of the app layout caused by the sidenav-layout. The desired ou ...

Delete a div when a button is clicked through JavaScript

I'm having an issue with a form I created that duplicates itself - I can't seem to get the 'x' button to remove the corresponding div as needed. I have placed both buttons outside of the div like this: <button type="button" id="cro ...

What causes the namespace to shift when utilizing npm for installing a library?

I've been attempting to integrate whammy.js into a project. The initial line in the source code is window.Whammy = (function(){ yet, after running npm i and inspecting node_modules, I discovered global.Whammy = (function(){ https://github.com/anti ...

Converting lists to JSON format in a C# web form

Utilizing JSON.stringify, I have implemented textbox autocomplete for a web-form that suggests city names based on user input. The goal is to retrieve relevant city names from the database and display them as suggestions in the autocomplete feature after t ...