简体   繁体   中英

set cookie using jquery, bodyclass from cookie on page load

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!

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM