Use HTML5 localstorage to maintain jQuery switch state on update page

I just found out about the HTML5 "localstorage" function. I am trying to implement it in conjunction with jQuery toggle to make the div stay in it in its last state when the page refreshes. This sounds like a great alternative to the liver! I have a lot of problems understanding how to implement it 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 try to execute localstorage as recognized 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 violin.

What I'm doing is definitely not working. I saw several similar questions here on SO this , which is a good example. However, this answer did not help me and seems very complicated.

, localstorage , .

.

+4
1

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()
    }
});

: Fiddle

+6

Source: https://habr.com/ru/post/1534768/


All Articles