How To Hide Banner After Click And Save With LocalStorage?
I'm new to Java Script and I can't figure out how to save the Information (localstorage) after the User clicks on Accept on my Cookie Banner - As soon as he clicks on Accept the Co
Solution 1:
Using getItem
and setItem
methods is enough to solve it
$(document).ready(function(){
// Check if the user already accepted it
if (window.localStorage.getItem('accept_cookies')) {
$('#CookieBanner').hide();
}
$("#Accept").click(function(){
// Save on LocalStorage
window.localStorage.setItem('accept_cookies', true);
$('#CookieBanner').hide();
});
});
You can read more about localStorage on MDN web docs: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
Solution 2:
localStorage
provides the two methods setItem()
and getItem()
to set and retrieve data. On page load, you can check for the value you set and hide the banner, or if it has not been set yet, register your click handler.
$(document).ready(function() {
if (window.localStorage.getItem('cookies-accepted') === '1') {
$('#CookieBanner').hide();
} else {
$("#Accept").click(function() {
$('#CookieBanner').hide();
window.localStorage.setItem('cookies-accepted', '1');
});
}
});
Post a Comment for "How To Hide Banner After Click And Save With LocalStorage?"