Preserve the active class position even after the page is refreshed using JavaScript

Utilizing the Flickity plugin, I have successfully created a tab-based content carousel. By incorporating the hash script available on GitHub, users can directly access a specific tab using URLs like example.com/#slide-1.

However, I am facing an issue where upon navigating away from the page and returning or refreshing it, the 'is-selected' class on 'tab-nav' resets itself. As a result, the selected tab does not correspond to the loaded content.

I am seeking a JavaScript solution that would allow the browser to remember the last 'is-selected' position so that when users refresh the page or return to it, the correct tab is still highlighted.

.slide-content {
  width: 100%;
}

.tab-nav a,
.tab-nav a:visited,
.tab-nav a:focus,
.tab-nav a:hover {
  display: inline-block;
  color: #000;
  text-decoration: none;
  padding: 24px;
  border: 1px solid #dedede;
}

.tab-nav .is-selected {
  background: #dedede;
}
<link href="https://unpkg.com/flickity@2/dist/flickity.min.css" rel="stylesheet"/>
<script src="https://unpkg.com/flickity@2/dist/flickity.pkgd.min.js"></script>
<script src="https://unpkg.com/flickity-hash@1/hash.js"></script>

<nav class="tab-nav">
<a class="slide is-selected" href="#slide-1">Slide One</a>
<a class="slide" href="#slide-2">Slide Two</a>
<a class="slide" href="#slide-3">Slide Three</a>
<a class="slide" href="#slide-4">Slide Four</a>
<a class="slide" href="#slide-5">Slide Five</a>
</nav>


<div class="carousel">
<div class="slide-content" id="slide-1">
<p>I'm Slide One</p>
</div>

<div class="slide-content" id="slide-2">
<p>I'm Slide Two</p>
</div>

<div class="slide-content" id="slide-3">
<p>I'm Slide Three</p>
</div>

<div class="slide-content" id="slide-4">
<p>I'm Slide Four</p>
</div>

<div class="slide-content" id="slide-5">
<p>I'm Slide Five</p>
</div>
</div>


<script>

var utils = window.fizzyUIUtils;

var carousel = document.querySelector('.carousel');
var flkty = new Flickity( carousel, {
  prevNextButtons: false,
  pageDots: false,
  hash: true
});

// Elements
var cellsButtonGroup = document.querySelector('.tab-nav');
var cellsButtons = utils.makeArray( cellsButtonGroup.children );

// Update buttons on select
flkty.on( 'select', function() {
  var previousSelectedButton = cellsButtonGroup.querySelector('.is-selected');
  var selectedButton = cellsButtonGroup.children[ flkty.selectedIndex ];
  previousSelectedButton.classList.remove('is-selected');
  selectedButton.classList.add('is-selected');
});

// Cell select
cellsButtonGroup.addEventListener( 'click', function( event ) {
  if ( !matchesSelector( event.target, '.slide' ) ) {
    return;
  }
  var index = cellsButtons.indexOf( event.target );
  flkty.select( index );
});
</script>

Answer №1

To easily retain the selected tab even after a page refresh, localStorage can be utilized to store the selector when the tab is clicked. Upon page load, the last selected tab can then be checked in localStorage and set as active. This method will prove effective for maintaining user selections through page reloads. As for navigating back, there are limited reliable methods available. One approach is to disable page caching in the browser by including the

Cache-Control: no-cache, no-store, must-revalidate
header in your pages. By doing this, if a user navigates back, the page will automatically reload.

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

Only implement $(document).on(...) for every JQuery request

As someone new to Jquery, I'm facing challenges in grasping its functionality. Specifically, my struggle lies in setting up an event listener on an i element with the class of .dataPickerIcon, which should respond to a click by inserting more HTML usi ...

Tips for successfully transferring an image through an XMLHttpRequest

I found this helpful resource at: I decided to test out the second block of code. When I made changes in the handleForm function, it looked like this: function handleForm(e) { e.preventDefault(); var data = new FormData(); f ...

Learn the process of dynamically loading scripts and their functions in Angular

At first, I had the following code statically placed in Index.html and it was functional. <script src="/le.min.js"></script> <script> LE.init({ token: 'token', region: 'x' }); </script> ...

Prevent clicks from passing through the transparent header-div onto bootstrap buttons

I have a webpage built with AngularJS and Bootstrap. It's currently in beta and available online in (German and): teacher.scool.cool simply click on "test anmelden" navigate to the next page using the menu This webpage features a fixed transparent ...

Turning off arrow key navigation for tabs in Material UI ReactJS

I'm currently utilizing ReactJS Material UI tabs navigation. My aim is to deactivate the arrow keys navigation of Tabs in Material UI. What I desire is to navigate using the Tab key, and upon pressing Enter, it should display the page beneath that ta ...

Convert alias query strings into parameters

I am currently working on a project that involves using node, express, and jade. I need to be able to access content through two different URLs: /Page/foo/bar and /Page?Foo=foo&Bar=bar The goal is for the top URL to act as an alias for the bottom o ...

Utilizing JavaScript functions alongside a button within a Handlebars template

My handlebars project has the following structure: Project | +-- server.js +-- package.json +-- package-lock.json | +-- public | | | |-- css | | | + -- style.css | +-- views | | | |-- layouts | | | | | + -- main. ...

Chrome Automatically Playing WebRTC Audio

My webapp has webrtc functionality, but I've noticed a strange issue. When connections are established between Chrome browsers, the audio is not played, while video is. However, this problem doesn't occur with Mozilla users. So... Chrome user 1 ...

Optimal banner image dimensions for responsive mobile display on various devices

What is the best way to ensure a banner image looks good on small and medium mobile devices, as well as tablets? ...

`Changing the iframe content dynamically with next and previous buttons: a step-by-step guide`

function displayPDF(fileSlNo){ var data = { pageMode: "PDF_DISPLAY", fileSlno: fileSlNo }; var d = $.param(data); var request = $ .ajax({ type: "GET", url:"folderNavigation.do?"+d, dataType : "TEXT", success: functio ...

Utilizing JQuery to merge variable identifiers

Imagine a scenario where the variables are structured this way: localStorage.var1a = 0; localStorage.varnum = 1000; Now, consider the following code snippet: for(x = 1; x < localStorage.varnum; x++){ if(localStorage.var.x.a > 0){ localStora ...

Is there a way to verify the presence of data and halt code execution if it is not found?

In my data, there is a table containing a total of 5 links. The first 2 links can vary in availability as they are dynamic, while the last 3 links are static and are always displayed. The dynamic links' data is deeply nested within the state object, s ...

Determine if two arrays share the same keys

Looking to compare two arrays and update them with matching keys while adding 0 for non-matching keys. For example: let obj1 = [ {"type": "Riesenslalom","total": 2862}, {"type": "Slalom", "total" ...

Save the uploaded file in Express to a custom directory on the system, avoiding the project's public folder

I have successfully integrated React on the front end to upload a file and receive it in Express.js. However, when storing the file in Express, it is currently being saved in the public folder. If I need to save the files in a non-public folder located at ...

The Bootstrap tabs are not correctly displaying the content

Hey there, I'm currently working on a project that involves using bootstrap tabs (BS4) within a form. One of the requirements is to have forward and back buttons for form navigation, and I'd like to leverage BS4's tab('show') fun ...

How to open a hyperlink in a separate background tab with JavaScript or jQuery

I am in need of a feature that automatically opens all links on a website in a new background tab when a user clicks on them. Despite searching extensively, I have not found a solution that works across all browsers. To implement this, I have referred to t ...

Influencing location preferences in Google's place search

I'm currently implementing a Google Places search feature and I need to enable "Location Biasing" for the GCC countries (UAE, Saudi Arabia, Oman, Kuwait & Bahrain). My goal is to achieve the functionality described in the following link: https://deve ...

Sort an array in descending order based on the key using JavaScript in Google Chrome

Having an issue with sorting an array in descending order by the key. It works perfectly in Firefox, but Chrome is displaying it in the original order. [["0", 0], ["1", 0.9], ["2", 597.5344192965547], ["3", 991.0326954186761], ["4", 1257.2580315846578], [ ...

Creating grid columns with evenly distributed widths that match the maximum width of the content within the items

Within a container grid, I have a variable number of child items with different widths. I am looking to use CSS grid to arrange them so that each column has equal width. The width of each column should be based on the widest child item. My initial approa ...

In Typescript, how can we reverse the order of an enum

I am encountering a particular challenge with the following code snippet: enum MyEnum { Colors = 'AreColors', Cars = 'AreCars', } const menuTitle = ((obj: MyEnum) => { const newObj = {}; Object.keys(obj). ...