'Cookie consent popup if accept do not show again
Supposing the user clicks the 'ACCEPT' link in the cookie consent popup, then the popup should not show again for 24hrs. Can someone show how me how to get this done?
<div id="cookieConsent">
<div id="closeCookieConsent">x</div>
This website is using cookies. <a href="cookies-policy" target="_blank">More info</a>. <a class="cookieConsentOK"><b>ACCEPT</b></a>
</div>
$(document).ready(function() {
setTimeout(function() {
$("#cookieConsent").fadeIn(200);
}, 4000);
$("#closeCookieConsent, .cookieConsentOK").click(function() {
$("#cookieConsent").fadeOut(200);
});
});
Solution 1:[1]
I have changed a little bit your code to store a local var with a value of true and expiration time of 10 seconds from the moment when user click on ACCEPT. Change this part to something like:
now.getTime() + (1000 * 60 * 60 * 24)
Every time page is loaded the script look for this stored var and if the expiration time is greater than the stored value then delete the stored var and show the cookie acceptance message again.
Here the code:
<div id="cookieConsent" style="visibility: hidden;">
<div id="closeCookieConsent">x</div>
This website is using cookies. <a href="cookies-policy" target="_blank">More info</a>. <a class="cookieConsentOK"><b>ACCEPT</b></a>
</div>
<script type="text/javascript">
$(document).ready(function(){
var consentStr = localStorage.getItem('cookieSeen');
if(!consentStr) {
$("#cookieConsent").css('visibility','visible').hide().fadeIn(200);
} else {
var consent = JSON.parse(consentStr);
const now = new Date();
if (now.getTime() > consent.expiry) {
localStorage.removeItem('cookieSeen');
return null;
}
//console.log('Cookie accepted');
}
$("#closeCookieConsent, .cookieConsentOK").click(function() {
const now = new Date();
const item = {
value: true,
expiry: now.getTime() + 10000,
};
localStorage.setItem('cookieSeen', JSON.stringify(item) );
$("#cookieConsent").fadeOut(200);
});
});
</script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jesús Noè Nogueiras |
