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

    Ads Blocker Detected!!!

    This site depends on revenue from ad impressions to survive. If you find this site valuable, please consider disabling your ad blocker.