Benedikt W Benedikt W - 3 years ago 160
Javascript Question

Age Verification Popup: Set cookie to remember decision

I am using the following code to display an age verification popup on a cigarette website:



// Popup Age Verification

$(function() {

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

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

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>





You can find the full code snippet here:
https://jsfiddle.net/xfk4m0xg/1/


I want to implement a cookie that remembers when the user clicks on the .button-yes button. The other button shouldn't have a feature like this. How can I realise it the best way?

Answer Source

Following implementation uses a cookie to store and retrieve the state of the age agreement. You should add a condition in JavaScript to identify the agreement state when the application starts. Also hide the popup by default using css.

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);
}

JavaScript using Cookies

$(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();
  });

});

JavaScript using localStorage

// Popup Age Verification

$(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();
  });
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download