Refreshed page causing hide/show div to reset

Hello there, I'm currently working on a web application and I need to implement some JavaScript code. The application consists of three sections, each with its own title and button. When the button is clicked, a hidden div tag is displayed. Clicking the button again will hide the div. Each button only works for its respective section, so pressing the Section1 button will show/hide the Section1 div, and so on for the other sections/buttons.

Specifically, I want to make it so that when one div is shown, the other two become invisible. This means that only one div can be displayed at a time on the mainpage.jsp for better usability.

Everything was going smoothly until I encountered two new features that I'm having trouble implementing. Firstly, the application needs to remember which div was displayed after a reload, rather than resetting all divs. I've tried using localStorage and sessionStorage without success, and as a newcomer to JavaScript, I suspect I may be missing something important.

The second feature is more of an aesthetic detail - I want the buttons to change their names between "Show Section (number)" and "Hide Section (number)" every time they are clicked. Unfortunately, my attempts from Stack Overflow resulted in errors where the button names did not update correctly and affected all buttons, not just those in the three sections.

I have hit a wall in my JavaScript knowledge and would greatly appreciate any guidance or help you may offer. Thank you for your time and assistance.

Here's a snippet of my code:

   // Checking localStorage  
    if ( (JSON.stringify(localStorage.getItem('activespoiler'))  !== 'none') && (JSON.stringify(localStorage.getItem('activespoiler'))  !== null) )
    {
        document.getElementById(localStorage.getItem('activespoiler')).style.display = 'block';
    }

    // Show/hide div content defined by id (spoiler1, spoiler2, spoiler3)
    function hideandshow(spoiler)
    {
        if(document.getElementById(spoiler).style.display === 'none')
        {
            document.getElementById(spoiler).style.display = 'block';
            localStorage.setItem('activespoiler',JSON.stringify(spoiler));
            
            // Closing other spoilers
            if (spoiler === 'spoiler1')
            {
                document.getElementById('spoiler2').style.display = 'none';
                document.getElementById('spoiler3').style.display = 'none';
            }
            else if (spoiler === 'spoiler2')
            {
                document.getElementById('spoiler1').style.display = 'none';
                document.getElementById('spoiler3').style.display = 'none';
            }
            else if (spoiler === 'spoiler3')
            {
                document.getElementById('spoiler1').style.display = 'none';
                document.getElementById('spoiler2').style.display = 'none';
            }
        }
        else if (document.getElementById(spoiler).style.display === 'block')
        {
            document.getElementById(spoiler).style.display = 'none';
            localStorage.setItem('activespoiler','none');
        }        
    } 
<button type="button" onclick="hideandshow('spoiler1')">Show/Hide Section 1</button>
  
    <div id="spoiler1" style="display:none">
            This is the hidden text SECTION-1! <br>
            <form action="mainpage.jsp" method="POST">
                <button type="submit">RELOAD PAGE SECTION-1</button> 
        </form>
    </div> <br><br>
<!-- Section 2 -->
<button type="button" onclick="hideandshow('spoiler2')">Show/Hide Section 2</button>
  
    <div id="spoiler2" style="display:none">
        This is the hidden text SECTION-2!
        <form action="mainpage.jsp" method="POST">
            <button type="submit">RELOAD PAGE SECTION-2</button> 
        </form>
    </div> <br><br>
<!-- Section 3 -->
<button type="button" onclick="hideandshow('spoiler3')">Show/Hide Section 3</button>
  
    <div id="spoiler3" style="display:none">
        This is the hidden text SECTION-3!
        <form action="mainpage.jsp" method="POST">
            <button type="submit">RELOAD PAGE SECTION-3</button> 
        </form>
    </div> 

Answer №1

Main highlight:

To automatically check the value upon page load, use this JavaScript code snippet:

// Verifying localStorage
    window.onload = function() {
        var reveal = localStorage.getItem('activereveal');
        if(reveal !== 'none'){
            document.getElementById(reveal).style.display = 'block';
            document.getElementById(reveal + '_button').textContent = 'Hide Section ' + reveal.slice(-1);
        }
    }

Additional point of interest:

Although not perfect, here is a functional variation:

  1. Assign an ID to your buttons like reveal + _button:

     id="reveal3_button"
    
  2. Update the script with the following code:

     // Verifying localStorage
     window.onload = function() {
         var reveal = localStorage.getItem('activereveal');
         if(reveal !== 'none'){
             document.getElementById(reveal).style.display = 'block';
             document.getElementById(reveal + '_button').textContent = 'Hide Section ' + reveal.slice(-1);
         }
     }
    
     // Toggle showing/hiding content in divs based on IDs (reveal1, reveal2, reveal3)
     function toggleContent(reveal)
     {
         var oldReveal = localStorage.getItem('activereveal');
    
         if(oldReveal !== reveal && oldReveal !== null) {
             document.getElementById(reveal).style.display = 'block';
             document.getElementById(oldReveal).style.display = 'none';
    
             document.getElementById(reveal + '_button').textContent = 'Hide Section ' + reveal.slice(-1);
             document.getElementById(oldReveal + '_button').textContent = 'Show Section ' + oldReveal.slice(-1);
    
             localStorage.setItem('activereveal', reveal);
         }
         else if (oldReveal !== null) {
             if (document.getElementById(reveal).style.display === 'none') {
                 document.getElementById(reveal).style.display = 'block';
                 document.getElementById(reveal + '_button').textContent = 'Hide Section ' + reveal.slice(-1);
             }
             else {
                 document.getElementById(reveal).style.display = 'none';
                 document.getElementById(reveal + '_button').textContent = 'Show Section ' + reveal.slice(-1);
             }
    
             localStorage.setItem('activereveal', reveal);
         }
         else {
             document.getElementById(reveal).style.display = 'block';
             document.getElementById(reveal + '_button').textContent = 'Hide Section ' + reveal.slice(-1);
             localStorage.setItem('activereveal', reveal);
         }
     }
    

Answer №2

Everything looks good in your code except for this one line:

localStorage.setItem('activespoiler',JSON.stringify(spoiler));

Try removing JSON.stringify and simply use sploiler to avoid adding extra "" to your tag id, like so:

localStorage.setItem('activespoiler',spoiler);

This change should make it work!

It's also recommended not to use inline styles in your HTML tags like this:

style="display:none"

Instead, you can use JavaScript to hide them during initial rendering at the beginning of your scripts, as shown below:

document.getElementById('spoiler1').style.display = 'none';
document.getElementById('spoiler2').style.display = 'none';
document.getElementById('spoiler3').style.display = 'none';

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

"PHP MySQL news error" - An unexpected error occurred

Just incorporated a news system using MySQL/PHP, it functions flawlessly; however, encounters errors when inserting HTML. For instance, inserting a YouTube video results in the addition of / or \ Can someone advise on what changes need to be made in ...

Displaying foreign exchange rates using Shield UI Chart

In my quest to access and display forex data, I have stumbled upon the incredible Shield UI Chart. After some experimentation, I successfully mastered the art of implementing ajax: $.ajax({ url: 'http://api.apirates.com/jsonp/update', dataTy ...

Accessing the parent scope from a directive within a nested ng-repeat in AngularJs

Seeking guidance on accessing the parent scope within a directive nested in an ng-repeat. Here is an example: <div ng-app="myApp" ng-controller="myCtrl"> <div ng-repeat="section in sections"> {{section.Name}} <div ng-rep ...

Unusual behavior observed while looping through an HTMLCollection returned by the getElementsByClassName method

After spending some time debugging, I discovered an issue with my function that changes the class of elements to modify their properties. Surprisingly, only specific elements were being affected by this change. It took me a while to troubleshoot and resolv ...

What is the best way to add Vue dependency using CDN?

For my project which is built using Kendo, Vue, .Net, Angular and jQuery, I need to incorporate https://www.npmjs.com/package/vue2-daterange-picker. <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-c ...

Troubleshooting directive not functioning properly with AngularJS ng-click

My HTML img tag is not responding to ng-click when clicked. I'm puzzled by this issue occurring in masonryPictureView.html Main page - home.html <ng-masonry> <ng-picture ng-items="projectdescription.pictures"></ng-picture> </n ...

Exploring the possibilities of custom layouts for specific routes within the pages directory in Next.js

I am interested in incorporating layout-based routing within my project's pages directory. I want to find a way to have a specific file, like the _app.tsx, that can only affect the files located inside a particular folder. This setup would operate si ...

Homepage featuring a stacked image background similar to Kickstarter

I am trying to replicate the stacked image effect seen on kickstarter.com. However, I am facing an issue where the images do not overflow on the screen as desired. The arrow indicates the area that needs to be filled with the image. Check out the image he ...

Creating a div that spans the entire height from top to bottom

Currently, I am faced with the following scenario: <div id=area> <div id=box> </div> </div> <div id=footer> </div> The "area" div is situated in the center and has a width of 700px with shadows on both the right and ...

Ways to eliminate all attributes and their corresponding values within HTML tags

Hey there, I'm trying to strip away all the attribute values and styles from a tag in html Here's my Input: <div id="content"> <span id="span" data-span="a" aria-describedby="span">span</span> <p class="a b c" style=" ...

What is the method for customizing the background color in a .vue file using Bootstrap?

Can anyone assist me in updating the background color of a div class from grey to white? The code is within a .vue file using Bootstrap and includes an enclosed SVG file. Here's the snippet: <div class="text-left my-3 bg-white"> <button var ...

Use Material UI TextField to prompt an email client or make a phone call

I am facing an issue with a MaterialUI TextField component. In certain situations, the TextField is disabled and I want it to be clickable as if it were an anchor tag leading to a phone number or email address. However, it seems that making the input behav ...

Incorporating a delay into looped HTTP requests while effectively utilizing Promise.all to track their completion

Greetings! In my current project, I am trying to introduce a 50ms delay before each subsequent HTTP request is sent to the server. Additionally, I aim to incorporate a functionality that triggers after all requests have been successfully made. To better e ...

Retrieving Data from Outside Source using AngularJS

Is there a way to retrieve JSON-Text-Stream data from a specific URL (e.g. SOMEURL/ean.php?id=4001513007704)? The returned result typically appears as follows: { "product": { "ean_id": "4001513007704", "title": "Gerolsteiner Mineralw ...

Is it possible to reorganize the order of elements in a

My goal is to create a flex column layout where the image appears first. However, I'm facing an issue with the code below, as it only changes the order when the flex direction is set to row (image on the left). It does not work for rows. </head> ...

Enhance the table using Django URL tag along with JQuery

I am currently working on a table that is being populated with user details and I would like to include a Django URL tag within the row, extracting the primary key in the process. Here is an example of what I am trying to achieve: function putTableData(re ...

Configuring Jest unit testing with Quasar-Framework version 0.15

Previously, my Jest tests were functioning properly with Quasar version 0.14. Currently, some simple tests and all snapshot-tests are passing but I am encountering issues with certain tests, resulting in the following errors: console.error node_modules/vu ...

adjusting the dimensions of images to ensure uniformity in size

After many attempts, I am still struggling to resize my image. Can anyone offer assistance? I want all images to have the same dimensions. Here is the HTML code: <link href='https://fonts.googleapis.com/css?family=Indie+Flower' rel='sty ...

Javascript handling scrolling and repositioning

When using the scrollBy() method in the window object of JavaScript, there are two arguments required. But what do these arguments actually represent? The resource I am currently studying from states that it is "the number of pixels to scroll by," but I am ...

Unable to load AngularJS thumbnails from JSON file? Learn how to showcase a larger image by clicking on the thumbnail

Working with AngularJS to retrieve image data from a JSON file has been successful for me. My next task involves loading all of the thumbnail images into the gallery div and populating the src, alt, and title attributes using ng-repeat. However, this part ...