I've looked over many of the similar questions and their answers and I'm stuck trying to get a working solution. I have multiple divs with the same classnames (they're created in a loop), and their toggled state needs to stay on refresh. Here's the html I'm working with:
<div class="bg-gray">
<div class="customize-card-md">
<input id="blog-1" class="customize-select" type="checkbox">
<label class="js-blog-select"></label>
</div>
</div>
On click, the class bg-gray is removed, which I'm using this:
$('.js-blog-select').on('click', function(event) {
$(this).closest('.customize-card-md').toggleClass('bg-gray');
})
This jquery works fine for now. As a side note, it's written this way because of styling for the label that allows the whole label to be clickable and also to deal with some bubbling/propagation issues with similar classnames on click. What I've tried, after reading over as much documentation as I could, is the following, which I'm trying to incorporate it to save into local storage. I'm quite new to using cookies and localstorage, but this is what I have so far that is not working:
if (localStorage.getItem('togglebg') === 'true') {
$(this).closest('.customize-card-md').toggleClass('bg-gray');
}
$('.js-blog-select').on('click', function(event) {
$(this).closest('.customize-card-md').toggleClass('bg-gray');
localStorage.setItem('togglebg', $(this).hasClass('bg-gray'));
})
On refresh the backgrounds are reverted back to gray, and not saved without a background as they should be. Any help would be greatly appreciated.