Add an active CSS class to a block upon page reload

I'm having a bit of trouble with my HTML code. Here's what it looks like:

<div class="side-button"> 
   <a href="/first"> First Option <a>
</div>
  <div class="side-button"> 
   <a href="/second"> Second Option <a>
</div>

My goal is to make it so that when a user clicks on one of the blocks, it becomes active and can be highlighted with a different color.

In my jQuery script, I've been attempting to add the class active to the clicked block:

jQuery(document).ready(function( $ ){
    $(".side-button").bind('click', function () {
      $(".side-button").removeClass("active");
      $(this).addClass("active");
    });
});

While this works while the next page is loading, after a redirect, the active class is not remembered. How can I make sure that the class active stays applied on the loaded page?

Answer №1

To store and retrieve data upon redirecting or loading a page, the local storage/session storage feature can be utilized.

 jQuery(document).ready(function( $ ){
        var retrievedClassName = localStorage.getItem('activeClass');
        if(retrievedClassName == "active"){
             //add active class to your element
        }
        $(".side-button").bind('click', function () {
          $(".side-button").removeClass("active");
          $(this).addClass("active");
          localStorage.setItem('activeClass', "active");
        });
    });

Answer №2

If you're wondering whether to use Window.sessionStorage or Window.localStorage, it's worth taking a moment to explore the differences by checking out:

HTML5 Local storage vs. Session storage

Session storage:

In the context of setting elements' href attribute and class within a click event, utilizing Window.sessionStorage can be useful. Storing and retrieving these values from sessionStorage on page load for element manipulation is exemplified in the following code snippet:

// Get
var status = sessionStorage.getItem("status");
var elHref = sessionStorage.getItem("elementsHref")
$("a[href$='"+elHref+"']").addClass(status);

$(document).ready(function($){
  $("a").bind('click', function () {
    // Set
    sessionStorage.setItem("status", "active");
    sessionStorage.setItem("elementsHref", $(this).attr("href"))
    $("a").removeClass(sessionStorage.getIt...

Local storage:

A similar approach can be taken using Window.localStorage. The scripting below demonstrates how this can be achieved:

// Get
var status = localStorage.getItem("status");
var elHref = localStorage.getItem("elementsHref")
$("a[href$='"+elHref+"']").addClass(status);

$(document).ready(function($){
  $("a").bind('click', function () {
    // Set
    localStorage.setItem("status", "active");
    localStorage.setItem("elementsHref", $(this).attr("href"))
    $("a").removeClass(localStorage.getItem("status"));
    $(this).addClass(localStorage.getItem("status"));
  });
});

Answer №3

$(document).ready(function(){
    $(".box").on('click', function () {
      $(this).toggleClass("selected");
    });
});

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

Move one of the numerous navigation bar links to the right using Bootstrap 4

I'm currently facing a challenge as I try to align one specific navbar link to the right. More specifically, in this scenario, I want only the logout link to be on the right side of the nav bar. I've experimented with various solutions such as us ...

Ways to send information from a child component to its parent component when a button is clicked in the

Being new to Angular, I am faced with a challenge of organizing a large form into smaller modular components. I have created multiple child components and integrated their selectors in the main parent component. In the parent component, there is a 'sa ...

Tips for creating a line break within a Bootstrap progress bar when the text exceeds the width of a div

By default, the progress bar displays text inside the portion that has progress. To ensure the text does not wrap prematurely, use white-space: nowrap; How can the issue of long text within a div be resolved without using JavaScript? Is there a way to ma ...

CSS animation shifting while altering its color palette

I have limited experience with CSS animations and my client is looking to achieve a hover effect similar to the one shown here when hovering over the contact button: Just to clarify, they are looking for: The square to move from left to right and then b ...

How can I display a list of relative urls in an android TextView?

I have a situation in my application where I am displaying a block of HTML content in a TextView, which has been extracted and parsed from a webpage. This HTML includes numerous links, with some being absolute and others relative. My goal is to allow the u ...

Showing a group of users in real-time as they connect using Socket IO

I've been working on setting up a system in Socket IO to create a list of individuals who join a 'party room'. The plan is to lock the party room once all players are present, and then display views to users. However, I've hit a roadblo ...

What is the method for incorporating opacity into the background color CSS attribute using a Fluent UI color?

Currently, my challenge involves applying opacity to a background color sourced from the fluent UI library, which utilizes Design Tokens. Typically, I would add opacity to a background color like this: background-color: "rgba(255, 255, 255, 0.5)" However ...

Is there a way to customize the animation for a button in material UI?

Trying to implement material UI in React and looking for a button that does not have the standard wave animation effect upon clicking, which you can see demonstrated here. Instead, I am searching for an animation that instantly fills the entire button wit ...

Can someone please provide me with the correct syntax for a jQuery AJAX PUT request that is JSON encoded?

Here is the ajax PUT request that I have written: jQuery.ajax({ url: url_lab_data+"backend/read/{\"f_anid\":"+anid+"}", type: "PUT", data: JSON.stringify({"read": 1}), ...

FoxyWeb Requests: Utilizing XMLHttpRequest in Firefox Extensions

While I've come across plenty of examples on how to create xhr requests from Firefox Add-ons, I'm currently exploring the new WebExtensions framework (where require and Components are undefined) and facing an issue with sending a simple XmlHttpRe ...

An alternative to Firebug for Internet Explorer

Can anyone suggest a suitable replacement for Firebug that is compatible with IE 7 and 8? I need a tool that allows me to edit CSS/HTML in real-time, debug JavaScript code, and visualize the positions of elements on web pages. Appreciate any recommendati ...

When the add button is clicked, a new radio button will be added along with the value entered in

Hello everyone, I'm working on a form that needs to display multiple radio buttons. Initially, I have set up one radio button with text and an option to add more buttons. Users can add multiple radio buttons by clicking on the "Add" button according t ...

Guide to adding dividing lines between columns with bootstrap

https://i.sstatic.net/FHO1v.pngCan someone help me with adding separators between columns in my HTML code? I've tried the code below but it's not working. Is there a way to achieve this? I've attached a screenshot of what I'm expecting. ...

Tips on setting up and managing configuration and registering tasks in Grunt

I've been working on a project that involves using grunt to process my Js and SASS files. The issue I'm facing is that every time I need to make a change, I have to run all the tasks in my gruntfile.js, even if it's just for one module or th ...

A JavaScript function for parsing a JSON string using the `new Function`

As I develop a script that parses the "rel" attribute of an anchor tag for a JSON String of settings, I am implementing code similar to this to convert the string into a JavaScript Object: var settings = new Function("return " + relAttribute); Would you ...

When resizing the browser window, this single horizontal page website does not re-center

I am in the process of creating my very first one-page horizontal website using jQuery and the scrollTo plugin. This site consists of 3 screens and initially starts in the center (displaying the middle screen). To achieve this, I decided to set the width o ...

What is the reason I am unable to upload personalized templates using <script> elements?

I have a dilemma where I need to swap out multiple templates from a library with my own custom ones without forking the original templates. When I include the templates in my index.html page like: <script type="text/ng-template" id="first-template"> ...

ItextSharp Pdf file generation does not include underlining or blue coloring for anchor text

Is there a way to add underline and blue color to anchor tags in a PDF generated using iTextSharp? The citation column needs a hyperlink in the Citation field, and the Citation string contains an anchor tag. How can I customize the formatting of anchor t ...

"Exploring Mocha and Chai: Tips for Generating a Comprehensive List of Errors in Test Cases

I am currently working on a unit test to validate a list of elements. Example: arr = [ { element : "aaa", validation : false }, { element: "bbbb", validation: true }, { element: "ccc", validation: false } While running my unit test, I encountered ...

How do I go about uploading the code as instructed on the platform's e-commerce details page?

.mk_01{ color: #000000; font-size: 30px; font-style: normal; font-family: Baskerville, "Palatino Linotype", Palatino, "Century Schoolbook L", "Times New Roman", serif; text-align: center; } .mk_02{ color: #000000; fon ...