Save the current active tab when refreshing the page

Struggling to find a way for the browser to remember the last active tab but haven't been successful.

function ShowMyDiv(Obj){
  var elements = document.getElementsByTagName('div');
 for (var i = 0; i < elements.length; i++) 
  if(elements[i].className=='tabcontent')
   elements[i].style.display= 'none';

 document.getElementById(Obj.rel).style.display= 'block';
 //------------------------------------

  var ul_el = document.getElementById('mytab_ul');
  var li_el = ul_el.getElementsByTagName('li');
 for (var i = 0; i < li_el.length; i++) 
  li_el[i].className="";

 Obj.parentNode.className="selected";
}

JAVASCRIPT

<ul id="mytab_ul" class="mytabs">
    <li class="selected"><a rel="tab_data" href="#data" onclick="javascript:ShowMyDiv(this);">Data</a></li>
    <li class=""><a rel="tab_vtu" href="#vtu" onclick="javascript:ShowMyDiv(this);">Vtu</a></li>
    <li class=""><a rel="tab_cabletv" href="#ctv" onclick="javascript:ShowMyDiv(this);">CTv</a></li>
    <li class=""><a rel="tab_nepa" href="#npa" onclick="javascript:ShowMyDiv(this);">NPA</a></li>
    <li class=""><a rel="tab_exampin" href="#pin" onclick="javascript:ShowMyDiv(this);">Pin</a></li>
    <li class=""><a rel="tab_spectranet" href="#spectranet" onclick="javascript:ShowMyDiv(this);">Spectranet</a></li>
    <li class=""><a rel="tab_smile" href="#smile" onclick="javascript:ShowMyDiv(this);">Smile</a></li>
    <li class=""><a rel="tab_a2cash" href="#cash" onclick="javascript:ShowMyDiv(this);">Cash</a></li>
</ul>

HTML

Can anyone guide me on how to achieve this?

I attempted to include this in my JS code

var selectedTab =  window.location.href.split("#")[1] ;
    var selectedId = $('a[href$=' + selectedTab+']:first').attr('rel');

    if (typeof selectedId === "undefined") {
         $('#tab_data').trigger("click");
    }
    else{
        $('#'+selectedId).trigger("click");
    }

But it still didn't work as expected

Answer №1

Utilize the browser's local storage for managing tabs. When a tab is clicked, set the active tab item like this:

localStorage.setItem("activeTab", tabId)

Upon page load, retrieve the active tab item with:

localStorage.getItem("activeTab")

For more information, check out: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

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

The Array map function is not displaying the list within a React component that is based on a Class

I am having trouble displaying a list of food items in my Parent component FoodBox.js and its child component FoodItems.js. I am using the map() method, but the <ul> element is showing up empty. Here is my code for FoodBox.js const FOOD_ITEMS = [ { ...

Iterating through a JavaScript object

Just starting out with JavaScript and trying to figure out how to iterate through a JSON result that has been converted into a JavaScript object. const url = 'https://api.mybitx.com/api/1/tickers?pair=XBTMYR'; fetch(url) .then(res => re ...

Refreshing an iFrame in NextJS from a different component

I am working on a NextJS application that includes a specific page structure: Page: import Layout from "@/components/app/Layout"; import Sidebar from "@/components/app/Sidebar"; export default function SiteIndex() { return ( < ...

Display a hidden div upon loading the page if a certain condition is met

As a beginner in this field, I am struggling to assist a friend with a project. He needs a simple quote form that can generate HTML quotes for his client on a private WordPress page. The form should display a specific div based on the radio button selecti ...

Error code -4058 ENOENT indicates that the file or directory does not exist. This issue is usually caused when npm is unable to locate a specific file

Trying to start a react project on my D: drive while having node installed on the C: drive resulted in an error: D:\react> npm start npm ERR! code ENOENT npm ERR! syscall open npm ERR! path D:\react/package.json npm ERR! errno -4058 npm ERR! ...

Is it possible to update only the necessary data using the Update Controller?

Update Controller exports.UpdatePanelMembers = (req, res) => { const { panelId } = req.params; if (panelId) { Panel.findOneAndUpdate( { _id: panelId }, { panelMembers: { member1: { memberId: req.body.pan ...

Is there a way to utilize code to invoke a method of an object? For example, calling MyObject.XVariable(//some function

I have a unique object that gets its data filled from an API call. let MyDog = { Name: 'Dog', } let arrayFunctions; fetchDogsFunctions(dogAPIUrl).then(res => { // The results variable contains an array of functions the dog can do, such as get ...

Transferring Python JSON object containing Japanese characters to JavaScript

My Python3 function generates a JSON object with the following structure: {'tags': {'releaseArtist': ['Shuichi Murakami', 'Nobu Caine', 'Electro Keyboard Orchestra', 'Mash', 'Loser', &a ...

Issue encountered when attempting to insert data via node into MySQL database

As a new Node developer, I am in the process of building some initial applications. Currently, I am working on inserting records into a MySQL database using Node. Below is an example of my post method: router.post('/add',function(req,res){ c ...

What is the best way to send an array of objects to a Node.js server?

What is the method for sending an array of objects with user data to the server for verification? I am attempting to pass orderform data to a server for validation and then display it on a different page after redirection. const addProductsToServer = (ev ...

Form an object using elements of a string array

Trying to convert a string array into an object. The string array is as follows : let BaseArray = ['origin/develop', 'origin/master', 'toto/branch', 'tata/hello', 'tata/world']; I want the resulting obje ...

Exploring the fundamentals of Express.js code base

I have been examining the express.js code and attempting to rewrite it to gain a better understanding of creating middlewares within a framework. However, the complex inheritance structure in the code is causing confusion for me. Here are some relevant co ...

Dotted JavaScript property within an object

Having trouble sorting an array of objects using the lodash orderBy function because it doesn't work when the iteratees contain a dot in the middle. For a better understanding of the issue, check out this plunker. plunker ar users = [ { 'us ...

JavaScript Discord bot encounters an issue: .sendMessage function is not recognized

Currently, I am developing a bot and testing its messaging functionality using .sendMessage method. (I prefer the bot not to send messages upon receiving any input, hence avoiding the use of: bot.on("message", function(message) {}); However, I am encoun ...

Encountering an Uncaught TypeError when attempting to set properties of null with useRef

I've been working on an app that requires access to the user's device camera in order to display live video on the screen. I've managed to achieve this by utilizing a video HTML Object and setting the media stream as its srcObject. Everythin ...

Handling Errors with Symfony 5 JSON Responses and VueJS Using Axios for Customized Error Messages

I need to show a personalized error message when my JSON response throws an error. Some of my services trigger an error like this: if (count($recipients) === 0) { throw new TransportException($this->carrierService::ERROR_NO_MAIL_ADDRESSES); } The ...

Should we employ getAttribute() or avoid it entirely? That is the ultimate query

Similar Topic: JavaScript setAttribute vs .attribute= javascript dom, how to handle "special properties" as versus attributes? On multiple occasions, I've encountered criticism in forums or Usenet about the way I access attributes i ...

Ways to set the base URL on the development server for a call to react-scripts start

I am facing an issue with configuring my primary PHP server to run the ReactJS dev server created using yarn start within a directory named /reactive on the PHP site (using nginx proxy_pass). The problem is that I cannot set the root of the node server to ...

Prevent a link from loading twice in jQuery's load() function if the parent page already

I am currently working on a page where data will be loaded into a lightbox using jquery. //index.php <script type="text/javascript" src="/jquery-1.11.0.min.js"></script> <a href='login.php'></a> //this will load ...

phpif (the current date is after a certain specific date, do

Can someone please help me solve this problem? I want to prevent echoing a variable if the date has already expired. Currently, my PHP code displays: Match 1 - April 1, 2015 Match 2 - April 8, 2015 What I need is for Match 1 to not be echoed if the cur ...