Trouble keeping HTML/Javascript/CSS Collapsible Menu closed after refreshing the page

My issue is that the collapsible menu I have created does not remain closed when the page is refreshed. Upon reloading the page, the collapsible menu is always fully expanded, even if it was collapsed before the refresh. This creates a problem as there is a large amount of content within this collapsible section.

Below is the basic code for the menu:

CSS:

//some CSS code here for styling, background color, etc.,
// .active is the key class

.active, .collapsible:hover{
background-color: #02538D;
}

HTML:

<button class="collapsible">Tutorials</button>
<div>
    <div class="content">
    <p>
      <?php
         //some PHP code here to output collapsible content
      ?>
    </p>
    </div>

    <div class="content">
    <p>
       <?php>
         //some PHP code here to output collapsible content
       ?>
    </p>
    </div>
</div>

JavaScript:

<script>
var coll = document.getElementsByClassName("collapsible");
var i;

for(i = 0; i< coll.length; i++) {
    coll[i].addEventListener("click", function() {
         this.classList.toggle("active");
         var content = this.nextElementSibling;
         if(content.style.display === "block") {
               content.style.display = "none";
         }
         else {
               content.style.display = "block";
         }
     });
}
</script>

I am new to JavaScript and suspect the issue lies in my script. Any help or guidance would be greatly appreciated. Thank you!

Answer №1

The issue with the code you shared is that the menu state is not retained when the page is refreshed, causing it to reset to its default status.

One workaround could be setting 'display:none;' as the default in your CSS to hide the menu on page refresh. However, this solution might not work if you also need the menu to remain visible between refreshes after users have interacted with it.

In such a scenario, you can utilize JavaScript to set a cookie when toggling the menu styles:

HTML

<button class="collapsible">Collapsible 1</button>
<div>
    <div class="menu-item">
    <p>Content 1</p>
    </div>

    <div class="menu-item">
    <p>Content 2</p>
    </div>
</div>

JAVASCRIPT

var coll = document.getElementsByClassName("collapsible");

for(i = 0; i< coll.length; i++) {
    var cookies = decodeURIComponent(document.cookie).split(";");
    for(i=0;i<cookies.length;i++) {
      if(cookies[i] == "menu-state=hide") {
                var content = coll[i].nextElementSibling;
        content.style.display = "none";
      }
    }
    coll[i].addEventListener("click", function() {
         var content = this.nextElementSibling;
         if(content.style.display === "block") {
               content.style.display = "none";
               document.cookie = "menu-state=hide";
         }
         else {
               content.style.display = "block";
               document.cookie = "menu-state=display";
         }
     });
} 

Link to Code Example

This implementation checks for a cookie named "menu-state" with a value of "hide" to initially hide the menu. The cookie is updated dynamically when the toggle action occurs.

For more information about managing cookies in JavaScript: Cookie Handling Guide

I hope this explanation helps you resolve your issue!

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

Guide on how to use JavaScript to upload media stream recorder blobs onto YouTube using the YouTube API

Using mediastreamrecorder.js, I am successfully recording video in 5-second blobs within the ondataavailable function. Here is an example of the code: mediaRecorder.ondataavailable = function(blob) { blob=blob; }; While I am a ...

Expressjs Error- ReferenceError: cors has not been defined in this context

While working on creating a backend using ExpressJs, I encountered an error when running the backend. app.use(cors()) ^ ReferenceError: cors is not defined at Object.<anonymous> (C:\Users\hp\Desktop\Entri\kanba\ ...

Accessing a JSON string correctly using JavascriptSerializer in JavaScript

When working with JavaScript, I encountered an issue where the data retrieved from a data table and converted to javascriptSerializer was not refreshing correctly when changing dataset selection parameters. The problem occurred when trying to populate a ne ...

strategies for chaining together multiple observables with varying data types and operations

Hey everyone! I'm facing a situation where I have a form with multiple select types, and the options for these inputs are coming from an API. I then take the data emitted from the HTTP request observable and feed it into my FormGroup, and everything i ...

Ways to extract a single digit from the total sum of a date in the format of 15-06-2015

Is there a way to extract a single digit from the sum of a number in date format, such as 15-06-2015? My goal is to convert the date format 15-06-2015 into a single-digit value by adding up the numbers. For instance: In the case of 15-05-2015, the output ...

Manipulating data in node.js as it arrives in separate chunks

Hey there, I am trying to make some changes to the data received from the server. All incoming data via the POST method is processed in chunks. <button id='helloButton'>Send hello!</button> <button id='whatsUpButton'>S ...

Allowing SVGs to be clickable without disrupting the functionality of YouTube videos

I'm experiencing an issue with the overlapping of the svg and YouTube elements. If you hover your mouse over, just to the right of the svg and click, instead of opening the video, it redirects you back to the previous page. Clicking on the area betw ...

Ensuring the script waits for the complete loading of iframe prior to

I'm faced with an issue on the website I'm currently working on. There's a Live Chat plugin integrated on an iframe, and I need to change an image if no agents are available. Interestingly, my code works perfectly fine when tested on the con ...

Displaying a portion of a React functional component once an asynchronous function call has been successfully executed

I am currently using material-ui within a React function component and have implemented its Autocomplete feature. I have customized it so that when the text in the input field changes, I expect the component to display new search results. callAPI("xyz") I ...

Is HTML5 data-target used for loading pages?

Currently, I am working with some HTML5 code: <li class="tile google" data-target-activation="click" data-target="loading"> <div> <a href="#">Search Google</a> <h2>Google</h2> </div> </li> Upon ...

Utilizing data in mongoose: A beginner's guide

I have two database models: User and Conversations. The User model has the following schema: const userSchema = mongoose.Schema({ username: String, logo: String, ..... }) and the Conversation schema is as follows: const conversationSchema = mongo ...

What could be causing issues with mysqli connection to the database?

Here is the content of my connect.php file: $mysql_hostname = "localhost"; $mysql_username = "root"; $mysql_password = "xxxxxxxx"; $mysql_database = "marrybrown_clean"; $bd = mysqli_connect ($mysql_hostname, $mysql_username, $mysql_password) or die (&apos ...

Maintaining accurate type-hinting with Typescript's external modules

Before I ask my question, I want to mention that I am utilizing Intellij IDEA. In reference to this inquiry: How do you prevent naming conflicts when external typescript modules do not have a module name? Imagine I have two Rectangle classes in different ...

Using JavaScript, you can filter an array of objects based on a specific search input

I am in the process of implementing a filtering feature for a list using React, but surprisingly, I haven't been able to find any useful resources online to guide me through this common task. Currently, I have an array of users that I need to filter ...

Is there a way to refresh the animation on dougtesting.net?

I'm working with the dougtesting.net library to create a spinning wheel. I've been trying to figure out how to reset the animation once it finishes, but I can't seem to find any information on it. My goal is to completely clear all states so ...

Error Alert: jQuery Ajax Not Executing

Looking to send form data to PHP using jQuery. Check out the code below. -------------HTML FORM-------------- <div id="createQuestionBlock"> <form id="createQuestionForm" action="" method="POST"> Question Code: <input id="code" ...

Prevent lengthy headers from disrupting the flow of the list items

I've encountered an issue while working on a website that features a list of items. When the title, such as "roller blinds," spans across two lines, it disrupts the layout below. How can I prevent this from happening without compromising on having lon ...

Is there a way to illuminate a complete row by simply hovering over a span within one of the columns?

If I want to change the background-color of a div with classes "row" and "highlightThisRow" when hovering over a span with the class "fromThisSpan", how can I achieve that? In a list, there are multiple rows with several columns. The span in question is l ...

Node.js express version 4.13.3 is experiencing an issue where the serveStatic method is not properly serving mp3 or

I am currently utilizing Express 4.13.3 along with the serve-static npm module to serve static assets successfully, except for files with mp3 or ogg extensions. Despite reviewing the documentation, I have not come across any information indicating that thi ...

Surprising CSS overflow error

Recently, I've encountered a CSS overflow issue while working on a responsive webpage. The problem seems to be stemming from the navigation menu. The declaration of "overflow-x: hidden" is specifically causing the trouble... Initially, I suspected i ...