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

It's impossible to remove a dynamically added class from a button

I'm facing an issue with adding and removing classes from a button using jQuery. I added a new class to the button, then removed it, but now when I click the button again I want to revert back to the initial class. Unfortunately, my code is not workin ...

What is the best way to reference an i18n entry within .json files?

I am in the process of creating a user interface using SAP UI5 and my goal is to make all text elements internationalized. Below is a snippet of my view in .xml format where I successfully retrieve text in different languages using placeholders enclosed i ...

Unleashing the Power of Object Destructuring in React Hooks

Here is a straightforward code snippet: import React from "react"; import { useForm } from "react-hook-form"; export default function App() { const { register, formState: { errors }, handleSubmit } = useForm(); return ( < ...

Capturing the Facebook Login Event to dynamically modify the content of the main webpage

My current project involves creating a Facebook-based login system using JavaScript. When a user clicks a button, I want one div to be replaced by another if the user is already logged in to Facebook. If they are not logged in, I prompt them to enter their ...

Is it possible to access the HTML template prior to Outlook applying any additional classes during rendering?

I recently received an email template created in a different platform via Outlook. I am attempting to recreate this email in the Salesforce Marketing Cloud Platform, but I am encountering numerous unnecessary tables, classes set by Outlook (MsoNormal, Ms ...

How can I show a legend entry for every column in Amcharts?

Take a look at this code snippet: http://jsfiddle.net/ouLed1fp/ How can I create a legend entry for each column in the chart? Also, is there a way to display the column names next to them, providing a clear legend? <div id="chartdiv" style="width: 10 ...

A new version of Primefaces has been released, introducing a sleek button feature with

How can I utilize the Primefaces version 10 button with a Font Awesome icon, resizing the icon without displaying the words ui:button? A and B are tests that I can resize successfully, but they are not buttons. C and D are buttons where the icon is resize ...

Is the append() function malfunctioning in jQuery?

Why is it copying two lines when I only want one line to be cloned on button click? Is there a way to make sure that only a single line is copied each time the button is clicked? Here is my code: $(function() { $('.add-more-room-btn').clic ...

Building a custom dialog box using Angular Material with HTML and CSS

I've been exploring different approaches to create a customized angular material dialog with a unique header using CSS/SCSS and the TailwindCSS framework. I am aiming for a specific visual effect, similar to what is shown in the figure below. desired ...

Personalize the way UIkit tooltips appear

I've been working on customizing a uikit tooltip for my checkbox. I managed to change the font and background color, but for some reason, I can't adjust the font size. I even tried adding a custom class without success. Do you think it's pos ...

Ensure that the text on the button is aligned to the right and is positioned directly

Looking to adjust the alignment of the menu icon on the left side of the menu text. Unsure about the best approach with my current CSS - should I utilize a grid layout to separate them on one side each, or perhaps use flexbox to align them inline? Below i ...

Is it possible for me to display dynamic content and utilize a template engine like (ejs)?

Currently, I am in the process of developing a weather application to enhance my skills with express and ejs. At the moment, I'm utilizing app.get to fetch data from darkSky's API successfully, and I can display it on my index.ejs page. My next ...

Decoding JSON data in a Webmethod from an AJAX call

I am faced with a challenge regarding passing a JSON object from JavaScript to a VB.Net WebMethod via an ajax request and then attempting to deserialize it. Despite successfully passing the object, I encounter an error during deserialization: Error convert ...

Transitioning in Vue.js can be triggered by changing a value up or down

My current transition block component is set up like this: <div v-if="!surveyResultIsReady" class="vh-md-40 position-relative" > <transition name="custom-classes-transition" enter-active-class="animated slideInRight" ...

Challenge with CSS selectors

Here is the HTML code I am working with: <label for="tx_alterneteducationcatalog_subscriberadd[newSubscriber][gender]" class="error" id="tx_alterneteducationcatalog_subscriberadd[newSubscriber] [gender]-error">This field is required.</label> ...

The term "Highcharts does not exist"

I'm encountering an issue with my code: <html> <head> <title><%=sAtaskaitaTitle%></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name=vs_targetSchem ...

I'm having trouble with AngularJS routes not functioning properly when accessed directly. I am using html5 mode in conjunction with

When accessing URLs directly in my Angular app either through the address bar or from external links, all routes default back to the home page. However, when navigating within the app, routes work as expected. I have come across similar issues on Stack Ov ...

Controller Function Utilizing Private Variable in AngularJS

After stumbling upon an Angularjs example online, I found myself perplexed. The code snippet in question is as follows: angular.module("testApp",[]).controller("testCtrl", function($scope){ var data = "Hello"; $scope.getData = function(){ ...

The Express application appears to be unresponsive, but the data has been successfully saved to the MongoDB database. An error with the

Currently, I am delving deeper into the MERN stack and working on a straightforward CRUD application utilizing it. One of the recent additions to the app includes validators implemented through express-validator for handling requests. However, an issue ari ...

Navigate through the rows and columns of an HTML table by utilizing Javascript with webdriver, specifically for Protractor in a non-angular environment

I need help with iterating through rows and columns using Selenium Webdriver. I am currently using Protractor for a non-angular web page. I have some Java code that works with the WebElement class to get the number of links, but now I need to transition th ...