Reputation: 98
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).
Upvotes: 2
Views: 320
Reputation: 148
you can use localStorage for that.
// write
window.localStorage.hasReadYourInfoBox = true;
// read
const hasReadInfoBox = !!window.localStorage.hasReadYourInfoBox
Upvotes: 0
Reputation: 51
Just save your switch state like localStorage.setItem('mySwithState', 'active')
And getting it when page loaded like localStorage.getItem('mySwithState');
Upvotes: 0
Reputation: 337560
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.
Upvotes: 2