Trouble with adding and checking for jQuery cookie

I have a form modal that asks visitors if they are over 21. If they click yes, i want to add a cookie (“over21”) and not show this form again for 30 days. It’s not working right now as it shows every time I restart the browser.

<div class="modal fade age" tabindex="-1" role="dialog" aria-labelledby="age" id="age">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      
      <div class="row">
            <div class="col-xs-12 ">
                <div class="text-center">
                    <img src="assets/img/black-cloister-logo.png">
                    <h3 class="yellow">Are you old enough for this quest?</h3>
                    <p class="white">Must be at least 21 to enter.</p>
                    <a href="https://www.google.com" class="btn btn-default" onclick="alert(message);">No</a>
                    <a id="old" data-dismiss="modal" class="btn btn-default">Yes</a>
                </div> <!-- class="center" -->
                
            </div>
        </div>

    </div>
  </div>
</div><!-- close modal -->


<script type="text/javascript">
    var message="Thanks for being honest! Come Back when you're 21";
</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
  
<script type="text/javascript">
$(document).ready(function() {
   if ($.cookie('over21') == null) {
       // testing- adding a cookie anyway
       //$.cookie('over21', 30);
       // open modal
       $('#age').modal('show');
       
   }
});

// if they click yes (over 21) add a cookie
$("#old").click(function() {
  //alert("adding cookie");
  $.cookie('over21', 30);
});

</script>

I don’t see an error here. Have you tried running it from an actual server (might also be localhost)? Setting cookies may not work from the file system…

Also please read the IMPORTANT! note on the jquery.cookie page. ;-)

It’s live now. Here is the link:
http://blackcloister.com

Seems to work. You don’t have by chance cookies disabled in your browser? ^^ BTW, for something like this you don’t actually even need cookies – just store the expiry date to the local storage. Like

var over21 = localStorage.over21 > Date.now();

if (!over21) {
  $('#age').modal('show');
}

$('#old').click(function() {
  var expiry = new Date;

  // Set the expiry date to 30 days from now
  expiry.setDate(expiry.getDate() + 30);
  loacalStorage.over21 = expiry.getTime();
});

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.