jquery - Using a cookie to save the state of a toggled division -
while i've found same question asked number of times here , on other sites, i've spent hours , hours trying answers work on site no avail; i'm plain stumped. possibly because i'm new javascript, self-taught, , i'm doing in first place try expand skills, i'm missing blatantly obvious else.
in event, on website have div sidebar, , i'm using jquery toggle , adjust parent div compensate absence when it's hidden via button. i'd able use cookie can refresh without returning default state, i've never used cookie before , every tutorial can find on subject , every answer can find similar question has resulted in code plain doesn't work reasons can't figure out.
here's jsfiddle of simplified version of website. (though toggle script isn't working there reason - works on website! missed when simplifying it, can't life of me figure out what.)
the html:
<div class="bgcontainer_center"> <div id="sidebar"> <p>sidebar content</p> </div> <div id="wrapper"> <div id="toggle"> <input type="button" value="toggle sidebar"> </div> <p>main content</p> </div> </div> the css:
.bgcontainer_center { position: relative; margin-left: auto; margin-right: auto; width: auto; max-width: 500px; background-color: #ff00ff; height: 100%; } .bgcontainer_center.clicked { max-width: 350px; } #sidebar { float: left; width: 25%; max-width: 125px; background-color: #00ff00; height: 100%; left: 0px; } #wrapper { width: auto; max-width: 350px; background-color: #0000ff; overflow-x: hidden; } and jquery:
$(document).ready(function () { $("#toggle").click(function () { $("#sidebar").toggle("slow"); $(".bgcontainer_center").toggleclass('clicked'); }); }); help me? bonus points if can explain me understand instead of giving me code works - i'm trying learn here! , feel free let me know if i've done else dumb coding.
edit: working version, tweaked function intended: https://jsfiddle.net/eo12xw79/3/
you can use localstorage store state.
see comments inline in code:
$(document).ready(function () { var sidebarvisible = localstorage.getitem('sidebar') == 'true'; // value localstorage $('#sidebar').toggle(sidebarvisible); // toggle sidebar, true: show, false: hide $('.bgcontainer_center').toggleclass('clicked', sidebarvisible); // add class true: add, false: don't add $("#toggle").on('click', function () { $("#sidebar").toggle("slow", function () { localstorage.setitem('sidebar', $('#sidebar').is(':visible')); // save visibility state in localstorage }); $(".bgcontainer_center").toggleclass('clicked'); }); }); demo: https://jsfiddle.net/tusharj/eo12xw79/2/
localstorage
the
localstorageproperty allows access local storage object.localstoragesimilarsessionstorage. difference that, while data stored inlocalstoragehas no expiration time, data stored insessionstoragegets cleared when browsing session ends - when browser closed.
doc: https://developer.mozilla.org/en-us/docs/web/api/window/localstorage
Comments
Post a Comment