Skip to Content

Solved: How to create a cookie when user click

Problem Symptom

How can I modify the function in the following code to create a cookie called bt-test which expires in 1 year when the user click?

$(document).ready(function(){
  $('#wt-cli-accept-all-btn, #wt-cli-reject-btn').on('click', function() {
     $('html.has-not-scrolled #desktop-header, html.has-not-scrolled #mobile-header, html.has-not-scrolled main').animate({top: '0px'});
  });

Follow the below solution steps to create a cookie when the user clicks.

Solution

To write a cookie:

document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";

You can put that inside of the onclick function.

Or you can try to use localStorage:

const aYear = 365 * 24 * 60 * 60 * 1000; // close enough
$(function(){
  $('#wt-cli-accept-all-btn, #wt-cli-reject-btn').on('click', function() {
    const now = new Date();
    const bt-test = localStorage.getItem("bt-test");
    const expiry = new Date(bt-test || now.getTime());
    const diff = now.getTime() - expiry.getTime()
    if (!bt-test || diff > aYear) {
      $('html.has-not-scrolled #desktop-header, html.has-not-scrolled #mobile-header, html.has-not-scrolled main').animate({top: '0px'});
      localStorage.setItem("bt-test",now.getTime()+aYear);
    }
  });
});

Reference

    Ads Blocker Image Powered by Code Help Pro

    Your Support Matters...

    We run an independent site that\'s committed to delivering valuable content, but it comes with its challenges. Many of our readers use ad blockers, causing our advertising revenue to decline. Unlike some websites, we haven\'t implemented paywalls to restrict access. Your support can make a significant difference. If you find this website useful and choose to support us, it would greatly secure our future. We appreciate your help. If you\'re currently using an ad blocker, please consider disabling it for our site. Thank you for your understanding and support.