Show information and organize tabs based on a localStorage variable

Recently, I came across a theme that intrigued me: . My goal is to utilize local storage in order to maintain the active tab even when the page is refreshed. However, I've encountered an issue where the site continues to display previous content and tabs even after clicking on a new tab.

   $(document).ready(function(){

        $("#tab-1").click(function() {
          window.localStorage.setItem("tab", "tab-1");
          window.localStorage.setItem("content", "tab-dashboard");
          $( ".cd-tabs__list > li > a" ).removeClass("cd-tabs__item");
          $( ".cd-tabs__panel" ).removeClass("cd-tabs__panel");
        });
        $("#tab-2").click(function() {
          // Store
          window.localStorage.setItem("tab", "tab-2");
          window.localStorage.setItem("content", "tab-workhours");
          $( ".cd-tabs__list > li > a" ).removeClass("cd-tabs__item");
          $( ".cd-tabs__panel" ).removeClass("cd-tabs__panel");
        });
        $("#tab-3").click(function() {
          // Store
          window.localStorage.setItem("tab", "tab-3");
          window.localStorage.setItem("content", "tab-my-profile");
          $( ".cd-tabs__list > li > a" ).removeClass("cd-tabs__item");
          $( ".cd-tabs__panel" ).removeClass("cd-tabs__panel");
        });
        $("#tab-4").click(function() {
          window.localStorage.setItem("tab", "tab-4");
          window.localStorage.setItem("content", "tab-admin");
          $( ".cd-tabs__list > li > a" ).removeClass("cd-tabs__item");
          $( ".cd-tabs__panel" ).removeClass("cd-tabs__panel");
        });
        $("#tab-5").click(function() {
          window.localStorage.setItem("tab", "tab-5");
          window.localStorage.setItem("content", "tab-company");
          $( ".cd-tabs__list > li > a" ).removeClass("cd-tabs__item");
          $( ".cd-tabs__panel" ).removeClass("cd-tabs__panel");
        });


        function defaultTab(){
            var defaultTabName = document.getElementById("tab-1");
        }

        function getTab(){
            var item = window.localStorage.getItem("tab");
            console.log(item);
            return item;
        }

        function getContent(){
            var item = window.localStorage.getItem("content");
            console.log(item);
            return item;
        }

        function activeTab(){
            console.log(getTab());
            if(false){
                defaultTab();
            }else{
                //var activatedTabName = document.getElementById("" + getTab())
                $( "#" + getTab() ).addClass( "cd-tabs__item--selected" );
                $( "#" + getContent() ).addClass( "cd-tabs__panel--selected" );
                window.localStorage.removeItem("content");
                window.localStorage.removeItem("tab");
            }
        }

        activeTab();



    });

I'm looking for a solution that allows me to click on the last tab displayed from local storage. How can this functionality be implemented?

Below is the HTML structure:

<nav class="cd-tabs__navigation">
    <ul class="cd-tabs__list" id="myTab">
        <li>
            <a href="#tab-dashboard" class="cd-tabs__item cd-tabs__item--selected" style="padding: 6px;" id="tab-1">
                <img src="images/dashboard.png" width="50px" height="50px" style="padding: 6px;">
            </a>
        </li>
        <li>
            <a href="#tab-workhours" class="cd-tabs__item" id="tab-2">
                <img src="/images/working-hours.png" width="50px" height="50px" style="padding: 6px;"/>
            </a>
        </li>

        <li>
            <a href="#tab-my-profile" class="cd-tabs__item" id="tab-3">
                <img src="/images/user.png" width="50px" height="50px" style="padding: 6px;"/>
            </a>
        </li>

        <li>
            <a href="#tab-admin" class="cd-tabs__item" id="tab-5">
                <img src="/images/settings.png" width="50px" height="50px" style="padding: 6px;"/>
            </a>
        </li>
        <li>
            <a href="#tab-company" class="cd-tabs__item" id="tab-5">
                <img src="/images/company.png" width="50px" height="50px" style="padding: 6px;"/>
            </a>
        </li>
    </ul> <!-- cd-tabs__list -->
</nav>

<ul class="cd-tabs__panels">
    <li id="tab-dashboard" class="cd-tabs__panel cd-tabs__panel--selected text-component">
     <!-- some content -->
    </li>

    <li id="tab-workhours" class="cd-tabs__panel text-component">
        <!-- some content -->
    </li>

    <li id="tab-my-profile" class="cd-tabs__panel text-component">
        <!-- some content -->
    </li>

    <li id="tab-admin" class="cd-tabs__panel text-component">
        <!-- some content -->
    </li>


    <li id="tab-company" class="cd-tabs__panel text-component">
      <!-- some content -->
    </li>
</ul> <!-- cd-tabs__panels -->

Answer №1

When clicking on #tab-dashboard, #tab-1 will not be triggered. To resolve this, you must update either #tab-dashboard to #tab-1 or vice versa in your code.

$("#tab-1").click(function() {
  window.localStorage.setItem("tab", "tab-1");
  window.localStorage.setItem("content", "tab-dashboard");
  $( ".cd-tabs__list > li > a" ).removeClass("cd-tabs__item");
  $( ".cd-tabs__panel" ).removeClass("cd-tabs__panel");
});

Additionally, in HTML:

<a href="#tab-1" class="cd-tabs__item cd-tabs__item--selected" style="padding: 6px;" id="tab-1">
    <img src="images/dashboard.png" width="50px" height="50px" style="padding: 6px;">
</a>

Edit: It might be more practical to bind not on href, but on another element like a js-class. This way, it can accommodate additional tabs without requiring changes to the code.

Take a look at this accordion for reference: https://codepen.io/Ravyre/pen/bYQOMx

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

Creating a scrollable panel using CSS is easy with a solid border and a panel element

Using Vaadin to design my front-end, I encountered an issue where adding border-style:solid to the style.css file resulted in a scrollable v-panel. How can I retain the solid style while removing the scrolling feature? Please refer to the screenshot for cl ...

Expo causing issues with TouchableOpacity in React Native app

I recently encountered an issue on my login page where I tried to use TouchableOpacity on the text "Already have an account? Sign in instead!" to navigate to the sign-in screen, but it didn't work as expected. After spending hours debugging my code, I ...

Jesting around with mocking console.error leads to test failures

The Issue: Currently, I am working on testing React components using Jest and Enzyme. In order to check for properties in development, I have incorporated the prop-types module. The prop-types module relies on console.error to alert when mandatory props a ...

Monitoring changes in the DOM with AngularJS

I have a unique situation where I need to monitor and recompile the entire DOM of a page whenever it undergoes any changes. While AngularJS handles this through databindings, I require a solution that goes beyond just bindings. My app is constructed using ...

I am facing an issue where adjusting the width of an iframe based on the browser using jquery is not

Having an issue with setting the height and width of a div and iframe based on browser window size using the following code: var newheight = $(document).height(); var newH = parseInt(newheight) - 170; var newHI = parseInt(newheight) - 215; ...

Having trouble with Highcharts-react not displaying on the first page load?

I am currently working on a React component that is responsible for rendering two Highcharts using the highcharts-react library. The data needed for these charts is coming from the state of a parent component and being passed down as props. However, upon l ...

Breaking down objects or arrays to extract specific values in React components

Some articles recommend using ES6 destructuring for React props & state as a best practice. For example: const { showModal, hideModal } = this.props; While I understand the benefits of cleaner code, I recently discussed with another developer who suggest ...

jQuery: Locate and eliminate any images in the text that appear after a specific group of tags if no images are present

Currently, I am in the process of developing a feed reader specifically designed to parse the Google News Feed. You can view and test the code on this Fiddle. My main challenge lies in removing titles and sources from the descriptions. Through my explorati ...

Troubleshooting issues with JavaScript progress bar functionality

I have implemented a progress bar using HTML5, JavaScript and Ajax to showcase file uploads in PHP. The issue I am facing is that the progress bar is not displaying the progress correctly. In addition to that, the echo statements in the PHP code are no ...

Is it feasible to render sub views, preserve history, and avoid re-rendering the entire view?

Transitioning my existing react app from using director to react-router has been a pleasant experience so far. However, I have encountered a challenge when it comes to maintaining history without re-rendering the entire page as easily as I could with direc ...

When a change is made in the parent component, the local state of the child component in ReactJS is automatically updated

I'm currently facing a challenge while implementing a custom dropdown filter for a table in react. Each column has a set of dropdown values with an Apply button. To handle this, I've created a child component that takes the dropdown values and s ...

Transition into darkness

Can anyone suggest a way to implement a React Native navigation transition that fades to black before transitioning to the next screen with a fade-out effect? I've searched extensively online but have only come across methods for changing screen opac ...

CSS - Overlapping elements on smaller screens due to being stacked

I am encountering an issue with a column of elements stacked below each other in my code. Here is a simplified version of my implementation: <div style="position: relative; height: 100%;"> <div style="position: absolute;">Really long text h ...

Javascript lags behind in utilizing Regex compared to PHP

My regex string is used to extract a value from CSS code like this: body { background: #000; } /* drapeDecalage: 10px */ I am trying to parse the commented drapeDecalage value. I have created a regex expression for that: (?<=\/\* drape ...

Tips for specifying headings for a particular div ID

I'm attempting to customize the font-family of the headings within my header section differently from the headings located elsewhere on the webpage. Unfortunately, I am encountering difficulties in ensuring that this style change only affects the spec ...

Performing two ajax calls within a non-existent div that has only just been appended

I've been developing a website similar to 9gag. I attempted to incorporate a voting feature created by someone else, as I'm not well-versed in AJAX requests, but it just doesn't seem to be functioning. My index.php file fetches five posts f ...

Using jQuery AJAX may cause the removal of Javascript functionality when running on Phone

I'm currently developing an application using jQuery and Phonegap. Within my javascript code, I utilize $.ajax to send requests to my web server in order to retrieve various sections of the app. These sections are essentially html snippets that are d ...

AJAX should prevent page refresh, but sometimes it forces it

This AJAX test page is a simple demonstration using JQuery. When the page is loaded, it displays a button (BUTTON1). Upon clicking on BUTTON1, it will execute react.php using script.js. The react.php will then replace BUTTON1 with BUTTON2 using a span elem ...

Contrasting actions observed when employing drag functionality with arrays of numbers versus arrays of objects

Being a newcomer to D3 and JavaScript, I'm hoping someone can help me clarify this simple point. I am creating a scatter graph with draggable points using code that closely resembles the solution provided in this Stack Overflow question. When I const ...

Displaying Images Beside Top Category Names in Magento

Is there a way to add small images next to the names in my top navigation menu? Here is an example of what I am looking for: Category1Name small_img | Category2Name small_img2 | Category3Name small_img3 Thank you EDIT: Below is the HTML code extracte ...