2

I want to offer a coupon code via a modal to visitors who have been the site before, but the last visit was more than 180 days ago.

Hashing out how to do this, I'm not sure if I should create a date variable to pass to the cookie or use timestamp. I'm generally new to javascript/jquery, so I'm not sure exactly how to code it, but I imagine it working something like this:

Check for cookie
   -If cookie does not exist, set it with timestamp/date.
   -If cookie does exist, check timestamp/date.
      -If timestamp/date is less than or equal to 180 days ago, reset timestamp/date with current time.
      -If timestamp/date is more than or equal to 181 days ago, show modal and reset timestamp/date with current timestamp/date.

This is what I have so far:

// Check if the cookie exists.
if (jQuery.cookie('lastVisit') == null) {
    var date = new Date();
    // If the cookie doesn't exist, save the cookie with the value of 1
    jQuery.cookie('lastVisit', 'date');
} else {
    // If the cookie exists, take the value
    var lastVisit_date = jQuery.cookie('lastVisit');
    // If last visit is in the last 180 days
    if (lastVisit_date <= 180) {
        // Reset cookie with new date
        jQuery.cookie('lastVisit', 'date');
    } else {
        // If last visit is past 180 days, show modal and reset cookie with new date
        jQuery('#myModal').reveal();
        jQuery.cookie('lastVisit', 'date');
    }
}

I'm not quite sure how to code this, any suggestions or suggested resources?

lexharter
  • 21
  • 2

1 Answers1

0

I made an example on CodePen where you can create a cookie.

Create one using a date 6 months ago...
Then, hit "Run" to see the 180 days comparison working.

Here is the relevant code:

var today = new Date();
if($.cookie("last-visit")){
    console.log("Cookie found!");
    //console.log( $.cookie("last-visit") );

    var cookieValArr = $.cookie("last-visit").split("-");
    var lastVisit = new Date();
    lastVisit.setFullYear( cookieValArr[0],cookieValArr[1]-1,cookieValArr[2] ); // YYYY, MM, DD - Months are zero based.
    //console.log(JSON.stringify(lastVisit));

    // I used a part of this other SO answer: http://stackoverflow.com/a/1458728/2159528
    var timeDiff = Math.abs(today.getTime() - lastVisit.getTime()); // Difference using milliseconds since january 1st, 1970
    var diffDays = Math.floor(timeDiff / (1000 * 60 * 60 * 24));     // Round to days
    console.log(diffDays+ " days since your last visit.");

    // Now is the time to check if more than x days.
    if(diffDays>180){
        console.log("Show modal!")
    }
}else{
    console.log("No Cookie.");
}
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64