简体   繁体   中英

Save toggled class state using js and/or cookies?

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).

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

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