Save toggled class state using js and/or cookies?

Viewed 149

I have a banner fixed at the bottom of my website that is open by default to display important information, I also have a button that can toggle it away if the user has read the notice and wants to hide it.

This is my js:

$(document).ready(function(){
    const   noticeToggle = document.querySelector('.notice__toggle'),
            notice = document.querySelector('.notice')

    noticeToggle.addEventListener('click', _ => {
        noticeToggle.classList.toggle('notice__toggle--toggled');
        notice.classList.toggle('notice--toggled');
    })
});

Is there a way I can use js, cookies or something else to save the state of this toggle whilst the user is on the website? Currently it only defaults to open when they navigate different pages (as expected).

3 Answers

You could use localStorage to store a flag to determine the state of the banner, something like this:

document.addEventListener('DOMContentLoaded', () => {
  const noticeToggle = document.querySelector('.notice__toggle'),
    notice = document.querySelector('.notice')
    
  if (!!localStorage.getItem('bannerDismissed')) {
    notice.classList.add('notice--toggled'); // remove the banner
  }

  noticeToggle.addEventListener('click', _ => {
    noticeToggle.classList.toggle('notice__toggle--toggled');
    notice.classList.toggle('notice--toggled');
    localStorage.setItem('bannerDismissed', 'true');
  })
});

Note that I removed the reliance on jQuery in the sample code as all it was used for was the document load event handler.

Just save your switch state like localStorage.setItem('mySwithState', 'active') And getting it when page loaded like localStorage.getItem('mySwithState');

you can use localStorage for that.

// write
window.localStorage.hasReadYourInfoBox = true;

// read
const hasReadInfoBox = !!window.localStorage.hasReadYourInfoBox
Related