0

I have a button which sets body class to .blackout

I'm using js-cookie to set the cookie, and the following code is associated with my button.

<script>
$('#boToggle').on('click', function(e) {
  $('body').toggleClass('blackout'); 
});
</script>

What I can't figure out is how to use Cookies.set('name', 'value'); from the link above to set the cookie with the .toggleClass AND how to retrieve it from cookie and apply it to body class.

Thanks in advance!

Community
  • 1
  • 1

1 Answers1

0

It looks like you want to maintain the state of your toggled class between sessions which could be done with Cookies but would perhaps be better suited for localStorage.

For the sake of completeness I'll demonstrate both approaches

With Cookies

To better understand the distinction between Cookies and Local Storage see this question, but I honestly think you could go with either approach. One advantage Local Storage has over cookies in this case is that you wouldn't need an additional library.

let state = Cookies.get('toggle');
$(body).toggleClass('.blackout', state)

With Local Storage

let state = localStorage.getItem('toggle');
$(body).toggleClass('.blackout', state)

With your updated snippet

var toggleLocalStorage = localStorage.getItem('toggle');
var toggleStatus = toggleLocalStorage ? toggleLocalStorage : false;

$('#boToggle').on('click', function(e) {
  $('body').toggleClass('blackout', toggleStatus);
  localStorage.setItem('toggle' toggleStatus);
});
jeanpier_re
  • 815
  • 1
  • 6
  • 23
  • Hmm! I've never tried local storage before now. And I couldn't seem to get it to work. My updated code is above for the toggle button (which I copied the wrong snippet... that was my junk code lol) – Sara Hubrich Jun 26 '17 at 04:52
  • Depends you'll need an event/action for `Cookie.set` or `localStorage.setItem`. The mechanism works the same, you could have it save on every click in which case you'd include the snippet I shared inside of your on 'click' handler. @SaraHubrich I've added a more concrete example for you to try. – jeanpier_re Jun 26 '17 at 16:46