4

I am trying to save a cookie or use localStorage (whichever is better) to remember when a visitor has clicked on a plus button to show/hide a div. Can anyone assist in helping make the below code work with a cookie or localStorage?

$('.plus').on('click', function(e) {
    $(".plus .icon .two").toggleClass('horizontal');
    $(".welcome-section").toggleClass('open');
    $(".welcome-header p").toggleClass('explore');
});
sergdenisov
  • 8,327
  • 9
  • 48
  • 63
Aaron
  • 525
  • 2
  • 9
  • 22
  • I don't see any attempt to use a cookie. – j08691 Feb 22 '17 at 19:20
  • I was trying to use if (element.hasClass("toggled")) { localStorage.setItem('toggled', 'true'); } else { localStorage.setItem('toggled', 'false'); } but all i was getting was errors and was getting in over my head. ugh – Aaron Feb 22 '17 at 19:30

1 Answers1

5

I prefer using localStorage:

Javascript:

var $content = $('.js-content');

if (localStorage.getItem('isVisible') === 'true') {
    $content.addClass('content_visible');
}

$('.js-button').on('click', function() {
    $content.toggleClass('content_visible');
    localStorage.setItem('isVisible', $content.hasClass('content_visible'));
});

CSS:

.content {
    display: none;
}

    .content_visible {
        display: block;
    }

HTML:

<button type="button" class="js-button">+</button>
<div class="content js-content">This is content</div>

JSFiddle

sergdenisov
  • 8,327
  • 9
  • 48
  • 63
  • This is great if you only have 1 element that you need to remember the state of, but what if you have multitudes more. Any idea on how to build a loop that will dynamically create multiple keys to check? – Gray Ayer Jul 06 '20 at 02:22
  • 1
    @sergdenisov you are a savior. Thanks man it took me 3 hours to find this solution of yours but it worked like a charm. Thanks again – Bilal Naseer Sep 22 '22 at 14:26