Azyme
Azyme

Reputation: 3

Local-storage didn't store the state of multiple slideToggle

I want to do a multiple vertical-menu with slideToggle and store the state of the toggle in local-storage, I don't understand why the state isn't stored.

I found this example (https://codepen.io/johnyrodni/pen/VVMXJx) who works, but when I try to past it to my real needs (https://codepen.io/azyme/pen/PrGNpW) there's no more local-storage.

<div id="dropdown-1">
        <div class="heading">
      Click me
        </div>

            <ul class="content">
                <li><a href="#">Link</a></li>
                <li><a href="#">Link</a></li>
        </ul>
</div>

<div id="dropdown-2">
        <div class="heading">
      Click me
        </div>

            <ul class="content">
                <li><a href="#">Link</a></li>
                <li><a href="#">Link</a></li>
        </ul>
</div>
$(document).ready(function() {
    var openTabs = [];


    $(".content").hide();

    $(".heading").click(function(){
        var $this = $(this),
        selector = $this.parent().attr('id') + ' .heading';

        if ($(this).next('.content').is(':visible'))
        {
            var pos = openTabs.indexOf(selector);
            openTabs.splice(pos, 1);

        }
        else
        {

            openTabs.push(selector);
        }

        localStorage.openTabs = openTabs.join(',');

        $this.next(".content").slideToggle();

    });

    if (localStorage.openTabs)
        $(localStorage.openTabs).click();
});

I expect that the state of the toggles will store in the local-storage

Upvotes: 0

Views: 62

Answers (1)

Devashish
Devashish

Reputation: 1290

This should fix it.

Replace this line:

localStorage.openTabs = openTabs.join(',');

with this:

localStorage.setItem('openTabs', JSON.stringify(openTabs.join(',')))

and this one:

if (localStorage.openTabs)
        $(localStorage.openTabs).click();

with this:

if (localStorage.hasOwnProperty('openTabs'))
     $(JSON.parse(localStorage.getItem('openTabs'))).click();

Upvotes: 1

Related Questions