Active tab in HTML

In my implementation based on this example code from https://www.w3schools.com/howto/howto_js_tabs.asp, I have a specific requirement. I want the tab for "Paris" to remain active even after the page is refreshed if the user has clicked on the button for "Paris".

<div class="tab">
  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">Enrollment</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')" id="secondOpen" >Student</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')" id="thirdOpen">Parents</button>
</div>

<div id="London" class="tabcontent">
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div id="Paris" class="tabcontent">
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p> 
</div>

<div id="Tokyo" class="tabcontent">
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>

<script>
function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}
// Is this correct?
first = document.getElementById("defaultOpen");
second = document.getElementById("secondOpen");
third = document.getElementById("thirdOpen");
if (second == ('active')){
    document.getElementById("secondOpen").click();
}else if(third == ('active')){
    document.getElementById("thirdOpen").click();
}else{
document.getElementById("defaultOpen").click();
}
</script>

This piece of HTML serves as an example, with the main focus on ensuring that the "Paris" tab remains active even after a page refresh when selected by the user.

Answer №1

Successfully implemented using local storage

See the Codepen demonstration here

function switchCity(cityName) {
  localStorage.setItem('cityName', cityName);
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  document.querySelector(`[data-value=${cityName}]`).className += " active";
}
localStorage.getItem('cityName') !== null ? switchCity(localStorage.getItem('cityName')) : switchCity('London')
body {font-family: Arial;}

/* Styling for tabs */
.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
}

/* Style for tab buttons */
.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
  font-size: 17px;
}

/* Button hover effects */
.tab button:hover {
  background-color: #ddd;
}

/* Active tablink style */
.tab button.active {
  background-color: #ccc;
}

/* Style for content within tabs */
.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: none;
}
<div class="tab">
  <button class="tablinks" data-value="London" onclick="openCity('London')">London</button>
  <button class="tablinks" data-value="Paris" onclick="openCity('Paris')">Paris</button>
  <button class="tablinks" data-value="Tokyo" onclick="openCity('Tokyo')">Tokyo</button>
</div>

<div id="London" class="tabcontent">
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div id="Paris" class="tabcontent">
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p> 
</div>

<div id="Tokyo" class="tabcontent">
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>

Answer №2

Here is my suggestion: 1. Save the ID of the tab in the browser's Local Storage (whenever you switch to another tab, make sure to update this variable) 2. Each time a user reloads the page, have a function retrieve this variable to activate the correct tab.

Answer №3

In order to persist state between page reloads, it is necessary to implement some form of lasting memory. Many websites achieve this through the use of session cookies...

For a detailed guide on how to work with cookies in JavaScript, refer to the tutorial available at w3schools: https://www.w3schools.com/js/js_cookies.asp

In your specific scenario, you will need to assign a key-value pair to hold the information about the selected tab. Whenever the user makes a selection, update the cookie's value accordingly. Upon page reload, retrieve the stored value from the cookie...

Answer №4

If you want to enhance your script, consider implementing the following:

Within the onclick function, make sure to save the active tab into localStorage for future reference.

function openCity(evt, cityName) {
  <------Insert your current code here---->
  localStorage.setItem('prevActive', cityName);
}

Additionally, after defining your onclick handler, introduce a new loading function and invoke it towards the end.

function load(){
    const cityName = localStorage.getItem('prevActive');
    if(cityName){   
        const tab = document.getElementById(cityName);
        tab.style.display = "block";
        tab.className += " active";
        const tablinks = document.getElementsByClassName("tablinks");
        for (i = 0; i < tablinks.length; i++) {
            if(tablinks[i].textContent === cityName){       
                tablinks[i].className += ' active';
                break;
            }
        }
    }
}
load();

To see this in action, check out the live demo

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

How can I adjust the container to fit the monitor's dimensions while still keeping the

I am currently facing an issue on my website where the main content div has a fixed height, causing it not to scale vertically on larger monitors. I attempted setting the CSS properties for the div to 'auto' in order to allow it to adjust to the ...

Is it possible to disable the save option on a PDF popup window?

When displaying a PDF using an embed tag, I have managed to disable print and content copying through document properties. However, I am struggling to find a solution to disable the save option that pops up. Is there a way to achieve this using JavaScrip ...

Exploring the world of BDD with Node.js and Angular in an actual web

Currently, I am in the midst of developing an application using nodeJs + yo angular-fullstck, starting with BDD and TDD practices. After searching through multiple resources, I have decided to utilize cucumber-js and Jasmin with the karma runner for testi ...

Column content merging in BS layout

Currently, I am exploring how to implement a two-column layout with the left column serving as a scrollable navbar. At this early stage of development, please excuse any imperfections in the code! One issue that arose involved using the .sidebar class wit ...

What causes all the accordion panels to toggle simultaneously in a ReactJs application?

When I click on the + button in my accordion, all the sections open at once. What could be causing this issue? Here is my code: const questions = [ { id:1, question: 'What is React?', answer: 'React is a JavaS ...

Update the class of the panel immediately prior to a click event

Is it possible to change the class before the animation starts or when opening/closing the panel? Currently, the class only changes after the animation has finished and the panel is already open or closed. Here is an example: http://jsfiddle.net/0b9jppve/ ...

The Ajax submit button is only operational for a single use

Check out my basic HTML form and JS setup: <body> <form> <label for="usrtext">Type your text here:</label> <br /> <textarea name="usrtext" id="usrtext" rows="25" cols="100"></textarea> ...

Is it possible to utilize mathematical operators such as multiplication, division, addition, subtraction, and exponentiation to transform a non-zero numerical value into

I am currently working with Oracle Siebel software which supports JavaScript expressions using only specific operators such as multiply, divide, subtract, add, and XOR (*, /, -, +, ^). Unfortunately, other operators like ! or ? : are not available for use. ...

Encountered a 500 internal server error when making a Jquery ajax POST

I am encountering an issue where the server is responding with a status of 500 (Internal Server Error) when trying to call my controller method. I am unsure why this error is occurring: <script type="text/javascript"> $('.dynamic').cha ...

Discovering the identification of a comment in JavaScript

Here is the code snippet I am working with: <a onclick="lel($(this),'212345555')" class="button"> <a onclick="lel($(this),'241214370')" class="button"> <a onclick="lel($(this),'248916550')" class="button"> & ...

React: Should we use useCallback when creating a custom Fetch Hook?

Currently delving into the world of React on my own, I've come across this code snippet for a custom hook that utilizes the fetch() method. import { useState, useEffect, useCallback } from "react"; import axios from "axios"; funct ...

Tips for validating user input in AngularJS without using a form tag

Within a popup, I am displaying HTML content that has been copied from another div and shown in the popup. I need to validate this input field to ensure it is required, and display an error message below the input box. <!-- HTML code for changing zip c ...

Sending a collection of data to a Django view using jQuery's ajax function

I am currently facing a challenge in passing a list of numeric values (ids) from one webpage to another using a jQuery ajax call. Despite successfully posting and reading a single value, I am struggling with passing and reading multiple values. Below is th ...

Guide to implementing bidirectional data binding for a particular element within a dynamic array with an automatically determined index

Imagine having a JavaScript dynamic array retrieved from a database: customers = [{'id':1, 'name':'John'},{'id':2, 'name':'Tim}, ...] Accompanied by input fields: <input type='text' na ...

Displaying and concealing table rows based on selected items

After spending a whole day trying to get this HTML/java script to work properly, I came across some code online that I used here. My goal is to have the "Colors*" row not displayed when the page loads, but to show the color options when a shirt size is sel ...

Uploading Images Dynamically with Ajax and jQuery in PHP

[Resolved Previous Issue] Recently, I obtained an image upload script that utilizes Ajax and jQuery. My goal is to restrict the maximum number of uploads to just 8 images. Any suggestions or advice would be greatly appreciated. Source of Download: ...

Is it possible to filter JavaScript Array while ensuring that select options do not contain duplicate IDs?

I am utilizing two datatables with drag and drop functionality. Each row in the datatables contains IDs. When I drag a row from table 1 to table 2, the data is stored in an Array. I have an addArray function that pushes the IDs into the Array, filters out ...

Enclosing floated elements within a parent div

Looking for a way to make a div wrap around a changing number of child elements without specifying a width for the parent? I've managed to get the content wrapping by floating both the child and parent elements, but I'm facing an issue when the ...

Adjust the positioning of two divs on mobile devices

My website has two main divs, one on the left and one on the right. The left div is styled with the classes: col-md-3 left_side And the right div with: col-md-9 right_side In the CSS file, the left_side and right_side classes only have padding, without a ...

Regex produces odd results in string processing

This particular JavaScript regular expression: homework.description = (homework.input.match(/((\(((\S\s?)\)?)*)|(about( \w*)*))/i)); When applied to the text: potato (potato) Produces this unexpected output: (potato),(potato), ...