Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use HTML5 localstorage to retain jQuery toggle state on page refresh

I just learned about the HTML5 "localstorage" function. I have been attempting to implement it in conjunction with jQuery toggle in order to cause a div to remain in it's most recent state when a page is refreshed. This seems like a great alternative to a cookie! I am having a lot of trouble understanding how to implement it in this way. Here is what I have tried so far:

HTML:

<div id="container"</div>
    <a id="foo" href="javascript:void(0);">Click Me</a>
    <div id="bar"></div>
</div>

CSS:

#container {width:200px; height:220px;}

#foo {
    display:block; float:left;
    width:200px; height:20px; 
    text-align:center;
}
#bar {
    display:none; float:left;
    height:200px; width:200px;
    background:#000000;
}

jQuery and attempt at localstorage as learned here:

$(document).ready(function(){
    $('#foo').click(function() {
    $(this).siblings().toggle();
    localStorage.setItem(display, block);
});
    var block = localStorage.getItem(block);
    if(block){
        $('#bar').show()
    }
});

Here is the fiddle.

What I am doing is definitely not working. I have seen somewhat similar questions here on SO this being a good example. However this answer hasn't helped me and seems very complex.

I am simply attempting to understand how to use localstorage at a very basic level in order to save a toggle state.

Greatly appreciate any advice or help.

like image 457
HelloWorld Avatar asked Apr 03 '14 06:04

HelloWorld


1 Answers

Try

$(document).ready(function () {
    $('#foo').click(function () {
        $(this).siblings().toggle();
        //you need to pass string values, your variables display & block was not defined
        localStorage.setItem('display', $(this).siblings().is(':visible'));
    });
    var block = localStorage.getItem('display');
    if (block == 'true') {
        $('#bar').show()
    }
});

Demo: Fiddle

like image 69
Arun P Johny Avatar answered Sep 25 '22 08:09

Arun P Johny