After closing the box, make sure to hold it securely

After clicking the button and closing my box with jQuery (Toggle), I want the state of the box to be remembered after refreshing the page. If the box was closed, it should remain closed upon refresh, and if it was open, it should stay open.
I am looking for a way to achieve this functionality in my code, as currently, any changes or data are lost upon page refresh.
For instance, I have written a code where clicking on a red square makes a blue square disappear, and clicking again makes it reappear. However, this behavior is not retained after refreshing the page.
DEMO
CSS :

.close-open {
    background: red;
    width: 50px;
    height: 50px;
    float: left;
}
.box {
    background: blue;
    width: 100px;
    height: 100px;
    float: left;
    clear: left;
    margin: 40px 0px 0px 0px;
}

HTML :

<span class="close-open"></span>
<div class="box">Test Box Toggle</div>

jQuery :

$(document).ready(function(){
  $(".close-open").click(function(){
    $(".box").toggle();
  });
});

Answer №1

To accomplish this task, there are several methods you can utilize. One approach involves utilizing Web Storage:

Javascript

$(document).ready(function(){
    var toggleStatus = localStorage.getItem("toggleStatus");
    if(toggleStatus == "false"){
        $(".section").hide();
    } 

  $(".toggle-button").click(function(){
    $(".section").toggle(
        function(){
            localStorage.setItem("toggleStatus", $(this).is(':visible'));
        });
  });
});

Try it out on JSFiddle

Using the localStorage feature, data can be stored without an expiration date. This means that the information will remain intact even after the browser is closed, and will still be accessible in the future.

Answer №2

To limit this feature to a specific session, you can utilize the following code snippet...

$(document).ready(function(){
                             if(sessionStorage.isHidden == "true" ){
                                 $(".box").hide();
                                 sessionStorage.isHidden = "false";
                             }
                             else
                                 sessionStorage.isVisible = "true";
  $(".toggle-button").click(function(){           
    sessionStorage.isHidden = $(".box").toggle().is(':hidden');
  });
});

See Demo

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

Converting a Powershell array into an HTML format

I have three arrays that I need to display on an HTML page: foreach($item in $array1){ // write array data to HTML } foreach($element in $array2){ // write array data to HTML } foreach($value in $array3){ // write array data to HTML } What is the ...

Can a webpage be redirected to another page while passing along the id from the original page?

https://i.sstatic.net/3LhYJ.png I have a page that displays shop names and addresses along with an edit function in views.py: def update_shop(request, id): context = {} # * fetch the object related to passed id obj_shop = get_object_or_404(VideoL ...

Custom Email Template for Inviting Msgraph Users

I'm currently exploring the possibility of creating an email template for the MS Graph API. I am inviting users to join my Azure platform, but the default email they receive is not very visually appealing. public async sendUserInvite(body: {email: < ...

Incorporating a JavaScript object into a DataTables JSON structure: A practical guide

I have integrated the datatables jQuery plugin into my project and I am looking to streamline the process by creating a shared function to easily call a datatable from multiple pages without duplicating code. To achieve this, I am attempting to define the ...

Unlocking the parent scope in a custom attribute directive

I am new to utilizing angular js. I came across a similar inquiry on How to access parent scope from within a custom directive *with own scope* in AngularJS? However, the solution provided did not work for my basic test. Here is the sandbox. http://jsfi ...

If you encounter a 1px space issue when resizing the viewport and using display: table; with fixed width cell

In our responsive projects, we are facing an issue with the display property set to table. Our table is wrapped within a container and set to 100% width, with one of the cells having a fixed pixel width. As we resize the browser window, we notice that the ...

Error: The ng-click directive is encountering a parsing syntax error. The token 'Object' is unexpected and is causing the error, it is expected to be enclosed in

When a user clicks on a point on a Google map, I am conducting reverse geocoding in the following manner: geocoder.geocode({'location': latlng}, function(results, status) { if (status === google.maps.GeocoderStatus.OK) { ...

The journey of a JavaScript file within an iframe devoid of any src attribute

Consider this scenario: In a folder labeled /jscript, there are two files named my_js_file1.js and my_js_file2.js. I also have an /index.html page structured like this: <html> <head> <script type='text/javascript' sr ...

Attach the element to the bottom of the viewport without obstructing the rest of the page

My challenge is to create a button that sticks to the bottom of the viewport and is wider than its parent element. This image illustrates what I am trying to achieve: https://i.stack.imgur.com/rJVvJ.png The issue arises when the viewport height is shorte ...

Is there a way to optimize the re-rendering and redownloading of images files in map() when the useState changes? Perhaps we can consider using useMemo

This Chat application is designed with channels similar to the Slack App. Currently, I am utilizing a map() function for filtering within an array containing all channel data. The issue arises when switching between channels, resulting in re-rendering and ...

Gathering information from an HTML form and displaying it through JavaScript by utilizing Bootstrap's card component

I've been working on integrating form data from my index.html page into a card component using Bootstrap. I've successfully collected the data in the backend, but now I'm struggling to display it on the frontend as a card component. Any help ...

Can an image be allowed to overflow outside of a div without changing the div's size?

Starting Point I am in the process of designing a layout with Bootstrap 4. Here's a rough representation of what I am aiming for: https://i.sstatic.net/7QTpk.jpg And here is the basic structure: <div class="row"> <div class="col-12 c ...

Is there a reason why I can't load all Google charts on one webpage?

I am trying to use the Google Charts API to display various charts on my web page. However, I seem to be encountering an issue where the last chart is not loading correctly. Can someone point out what I might be missing in my code? I would greatly apprecia ...

Javascript event triggering twice

I have created this code snippet to showcase the issue I am facing. main.php <body> //some html <script> function fx1(){ $(".elem").click(function(){ alert("hello"); }) } </script> //some html again include sub-acc.php & ...

What is the best way to refresh my useEffect hook when a State change occurs in another component's file in ReactJS?

Seeking to execute an API call within useEffect() and aiming for the useEffect() function to trigger every time new data is appended to the backend. To achieve this, a custom button (AddUserButton.js) has been created to facilitate adding a new user to the ...

Implementing fetch API in middleware in Next.js

Currently, I am utilizing a middleware in Next.js (https://nextjs.org/docs/advanced-features/middleware) for my project. However, I am encountering an issue when trying to send a request to the API. The error message displayed is: "unhandledRejection: Ty ...

Issue with vue-cli3 eslint and compiler arising from conflicting vue/script-indent settings

Whenever my .eslint.js file includes this rule: "vue/script-indent": [ "error", 4, { "baseIndent": 1, "switchCase": 1, } ] and I save it, an error pops up: Error: Expected indentation of 32 spaces but only found 24 spaces ...

Exploring Beautiful Soup to extract child values based on their relationships with their siblings and parents

I'm having trouble extracting the text I-want-ya from: <div class="field"> <div class="labelx"><a class="clickme" href="#h_group123" rel="#h_group123" title="Group">* Group</a></div> <div class="input">I-want ...

Ways to verify if a div is empty following an ajax request

When trying to load a php page into a div, I encountered an issue where the content of the div appeared empty. Despite attempting various methods to check if the div contained any html content after loading, I was unable to find a solution. ...

Issue observed with the functionality of checkAll and uncheckAll after a user interacts with a single checkbox

After completing an Angular course on Udemy, I decided to implement a custom checkbox in my Angular app. However, I encountered an issue where the UI was not updating properly when using checkAll and uncheckAll functions after the user interacted with an i ...