Search code examples
jquerycookiespopupjquery-cookie

1 hour Cookie for Age Verification pop up


I have an age verification pop up that installs a cookie in order to remember user's action for a certain period of time. I have done this following other post here at stack overflow, but I have some doubts.

css

#popup {
  z-index: 1000;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  position: fixed;
  display: none;
  background-color: rgba(0, 0, 0, 0.8);
}

JS using Cookies (doesn't work)

$(function() {

  //Check it the user has been accpeted the agreement
  if (!(document.cookie && document.cookie == "accepted")) {
    $("#popup").show();
  }

  $('[data-popup-close]').on('click', function(e) {
    var targeted_popup_class = jQuery(this).attr('data-popup-close');
    $('[data-popup="' + targeted_popup_class + '"]').fadeOut(350);

    //Set a cookie to remember the state
    document.cookie = "accepted";

    e.preventDefault();
  });

});

JS using local storage

$(function() {

  //Check it the user has been accpeted the agreement
  if (!localStorage.getItem('accepted')) {
    $("#popup").show();
  }

  $('[data-popup-close]').on('click', function(e) {
    var targeted_popup_class = jQuery(this).attr('data-popup-close');
    $('[data-popup="' + targeted_popup_class + '"]').fadeOut(350);

    //Set a cookie to remember the state
    localStorage.setItem('accepted', true);

    e.preventDefault();
  });
});

My first question is why using Cookies does not work?

And the second one is that I would like to have the cookie for a certain period of time as mentioned above. Now with the localStorage method just show the popup once and if I accept and refresh the page is not showing the pop-up anymore but I guess that won't show it for ever. I have tried using this inside the function to control for how long the cookie will be active.

$.cookie('accepted','yes', {expires: 7, path: '/'});

I guess that '7' means 7 days, but if put '0' it does the same. Is it posible to just have the cookie for one hour in order to see if it is working right?

Many thanks as usual for your help.

Br


Solution

  • Days is just a number being multiplied to seconds later in the plugin. If you want the cookie to be stored for 1 hour, then you can try

    $.cookie('accepted','yes', {expires: 1/24, path: '/'});
    

    You may try the following code

    $(function() {
    
      //Check it the user has been accepted the agreement
      if (!$.cookie('accepted')) {
        $("#popup").show();
      }
    
      $('[data-popup-close]').on('click', function(e) {
        var targeted_popup_class = $(this).attr('data-popup-close');
        $('[data-popup="' + targeted_popup_class + '"]').fadeOut(350);
    
        //Set a cookie to remember the state
        $.cookie('accepted','yes', {expires: 1/24, path: '/'});
        e.preventDefault();
      });
    
    });