0

i want to set a show/hide js script that is using localstorage on by default.

$(document).ready(function () {
  var sidebarVisible = localStorage.getItem('sidebar') == 'true';
  $('#sidebar').toggle(sidebarVisible);
  $('.bgcontainer_center').toggleClass('clicked', sidebarVisible);

  $("#toggle").click(function () {
    $("#sidebar").toggle("slow", function () {
      localStorage.setItem('sidebar', $('#sidebar').is(':visible'));
    });

    $(".bgcontainer_center").toggleClass('clicked');
  });
});

This is the link to it https://jsfiddle.net/eo12xw79/67/

I can't seem to find how to set it on by default.

Edison D'souza
  • 4,551
  • 5
  • 28
  • 39
Dest
  • 1
  • Do you want the main content to be the default one? – EugenSunic May 06 '18 at 09:50
  • It is working fine in my case....' – Nishant Dixit May 06 '18 at 09:57
  • Could just check for not false and leave the rest as it is, since all that is not false is true in your case (first time && visible). Also be aware that not all settings and browsers allow access to localStorange, in which case the check on not false is also better. – Lain May 06 '18 at 10:18

1 Answers1

1

The reason it isn't toggled is because the sidebar key isn't present in the browser's localstorage the first time we visit the page.

There is a very simple solution, just have to check if the sidebar key exists in the localstorage and if not, create it.

$(document).ready(function () {

    // BEGIN
    if(!localStorage.getItem('sidebar')) {
        localStorage.setItem('sidebar', 'true');
    }
    // END

    var sidebarVisible = localStorage.getItem('sidebar') == 'true';
    $('#sidebar').toggle(sidebarVisible);
    $('.bgcontainer_center').toggleClass('clicked', sidebarVisible);

    $("#toggle").click(function () {
        $("#sidebar").toggle("slow", function () {
            localStorage.setItem('sidebar', $('#sidebar').is(':visible'));
        });

        $(".bgcontainer_center").toggleClass('clicked');
    });
});

EDIT : I think it's useless, why ?
Because you will use the localstorage for a single variable that has no real importance.
After, this is only a personal opinion, it depends on your needs.

DUPLICATE : How to check whether a Storage item is set?

  • 1
    Delighted to have been able to help you. You can check the checkmark to inform the community that your question has been resolved. –  May 06 '18 at 10:03
  • localStorage.getItem('sidebar') == null instead just write !localStorage.getItem('sidebar') – EugenSunic May 06 '18 at 10:07
  • 1
    @eugene_sunic yes it's true, i've edited my post thank you ! :D –  May 06 '18 at 10:10