Tips and tricks for retaining the collapsed state upon reloading Bootstrap 5

Just diving into the world of bootstrap and javascript. How do I save the collapsed state to make sure it stays even after refreshing the page?

<p>
  <button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
    Collapse Button
  </button>
</p>
<div class="collapse" id="collapseExample">
  <div class="card card-body">
    Just started an exciting engineering project at Makers Academy. Delving into more complex areas, with a quick guide on adding likes to posts.
  </div>
</div>

Here's my attempt using Javascript.

$(document).ready(function () {
    $(".collapse").on("shown.bs.collapse", function () {
        localStorage.setItem("coll_" + this.id, true);
    });

    $(".collapse").on("hidden.bs.collapse", function () {
        localStorage.removeItem("coll_" + this.id);
    });
    
    $(".collapse").each(function () {
        if (localStorage.getItem("coll_" + this.id) === "true") {
            $(this).collapse("show");
        }
        else {
            $(this).collapse("hide");
        }
    });
});

Answer №1

Yes, it is functional - you can check out this demo.

It appears that you are utilizing the $ notation, therefore jQuery must be loaded as well. Ensure that jQuery is loaded prior to bootstrap.js.

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

Conditional compilation in Laravel Mix allows for specific code blocks to be

I'm currently working on a Laravel project and I need to introduce some conditional statements. Within the root folder of the project, there's a file called module_statuses.json which contains JSON variables like this: { "Module1": true, ...

The submission of the form with the ID "myForm" using document.getElementById("myForm").submit() is

<form name="formName" id="formName" action="" method="post" autocomplete="off"> <input type="hidden" name="text1" id="text1" value='0' /> <input type="button" name ="submit" onClick="Submit()" value="submit"> ...

EmeraldSocks Tweenmax motion design

I need help with Tweenmax animation. I'm attempting to animate an id selector, but nothing is happening. Both the selector and content are unresponsive. Can someone assist me? Here is the code: <!DOCTYPE html> <html> <head> ...

What is the optimal approach for moving the dashboard to a separate subdomain in a static Next.js-generated landing page?

Our current setup includes several static pages generated by Next.js using the command next build && next export These pages are hosted on AWS S3. I am wondering if we should create a new app for building a dashboard with Firebase authentication ...

Methods for validating ajax response with Jasmine

I'm a newbie when it comes to jasmine and I'm trying to figure out how to verify if a specific node is present in the ajax response. Currently, I'm using grunt to run jasmine from the command line and have successfully tested if a function i ...

Animation that responds to scrolling movements

Is there a way to animate text based on scrolling? <p class="class">TEXT</p> transform:translateX(-500px);opacity:0; transform:translateX(0px);opacity:1; ...

Tips for personalizing the export grid menu in angular-ui-grid?

My grid includes an external "Show Details" option that adds extra columns to the grid when clicked. https://i.sstatic.net/Fu2Qp.png The problem arises with the options for "Export all data" and "Export visible data," which can be confusing in this scena ...

Troubleshooting Vue.js and Laravel: Having trouble loading new image files, while the older ones load just fine

Currently, I am working on a project that involves Vue.js and Laravel. In this setup, Vue is located inside the resources/js directory of the Laravel project. My current issue revolves around loading an image from the resources/js/assets directory. While ...

Even though I am attempting to submit a form without refreshing the page using Ajax, it is still causing

I've searched high and low, read through numerous examples on various forums, and attempted to find the solution to my query but unfortunately, it still eludes me. Here's the particular scenario I'm facing: Main.php The main.php page featu ...

Unexpected Behavior when Passing @Input() Data Between Parent and Child Components in Angular 2 Application

I am currently in the process of abstracting out a tabular-data display to transform it into a child component that can be loaded into different parent components. The main aim behind this transformation is to ensure that the overall application remains "d ...

An issue arises when trying to loop using a while loop within an HTML structure

I have a small project with a predefined format, where I need to select a value from a dropdown menu and use that value to fetch data from a database and display it in HTML. While I am able to retrieve the data from the database based on the selected value ...

How can images be resized according to screen resolution without relying on javascript?

Looking to use a large banner image on my website with dimensions of 976X450. How can I make sure that the image stretches to fit higher resolution monitors without using multiple images for different resolutions? ...

I'm encountering an issue where my information doesn't seem to be getting through to the Django

For some reason, the data I am trying to post to /api/recipe/recipes/ is not showing up in my HTML {% extends 'base.html' %} {% block content %} <!DOCTYPE html> <html> <head> <script src="h ...

Encountering a 404 error when attempting to use the jQuery .load() function with parameters that include periods ('.')

I am attempting to invoke a controller function using the .load() method, but encountering an error which might be caused by the encoding of '.'. The call I am making is as follows: $("#main-content").load( url + "/" + encodeURIComponent(text ...

Using null or undefined for ternary operator formatting in React applications

When styling a component, what should be used if a specific condition is not fulfilled: null, undefined, or something else? For example: errorStyle: { right: locale === Locales.ARABIC ? 0 : null, left: locale !== Locales.ARABIC ? 0 : null, .. ...

Issues arise when attempting to retrieve information in NextJS from a local API

One of my coworkers has created a backend application using Spring Boot. Strangely, I can only access the API when both our computers are connected to the same hotspot. If I try to access the other computer's API and port through a browser or Postman, ...

Creating a conditional interface based on props in TypeScript: A step-by-step guide

What is the most effective way to implement conditional props in a component that can be either a view or a button based on certain props? Let's take a look at an example called CountdownButtonI: class CountDownButton extends Component<CountdownBut ...

console fails to return a function even when it is defined

After clicking the "stopCrash" button, I want the function backAgain to be executed 2 seconds later. However, I am encountering an error in the console: Uncaught TypeError: this.backAgain is not a function. Do you have any suggestions on how to fix this i ...

Generating Legible JavaScript Code from TypeScript

I am looking to maintain the readability of my compiled JS code, similar to how I originally wrote it, in order to make debugging easier. However, the typescript compiler introduces several changes that I would like to disable. For instance: During compi ...

Failure to display Bootstrap 5 modal

My attempt to implement a modal by following the documentation failed when clicking on a button. Here is what I tried. Within a form, I included a button: <div class="col-12 offset-md-10"> <button type="button" class="b ...