Jackson Cunningham
Jackson Cunningham

Reputation: 5073

Check returning visitors using cookies

I have a blog that requires users to signup via email in order to view the full post. I want to skip this requirement if a user has already signed up.

Here's how it works.

  1. User visits page, if cookie is presen then show content
  2. If cookie is not present, user must signup
  3. User signs up, cookie created.

The problem with my code is that it's post specific. e.g. Let's say we have Post A & Post B. If user opts in Post A, they will need to opt in again on Post B which is not good.

If they opt in on Post A, I want to recognize the cookie on Post B as well.

How can I adjust my code?

     if (document.cookie.indexOf("entered_email")>=0) {
          jQuery('.hidden-blog').slideDown();   
    }



$('.snp-subscribeform').on('submit', function() {   
      $('.hidden-blog').slideDown();
      document.cookie="entered_email=true;expire=06/12/2018";
    });

Upvotes: 0

Views: 1152

Answers (1)

jfriend00
jfriend00

Reputation: 707218

You need to set the path on the cookie to "/" which then allows any page on that site to see the cookie. When you do not set a path for the cookie value, it defaults to the path of the current page which restricts the visibility of that cookie to that path only.

Here are some utility functions for dealing with cookies that allow you to set the path or will default the path to "/".

Using these, your code would look like this:

if (readCookie("entered_email") === "1") {
    jQuery('.hidden-blog').slideDown();   
}

$('.snp-subscribeform').on('submit', function() {   
    $('.hidden-blog').slideDown();
    // cookie path in this function defaults to "/" so all pages on the
    // site can access the cookie
    createCookie("entered_email", "1", 365 * 3);
});

And, here's the utility cookie management functions:

// createCookie()
// name and value are strings
// days is the number of days until cookie expiration
// path is optional and should start with a leading "/" 
//   and can limit which pages on your site can 
//   read the cookie.
//   By default, all pages on the site can read
//   the cookie if path is not specified
function createCookie(name, value, days, path) {
    var date, expires = "";
    path = path || "/";
    if (days) {
        date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires=" + date.toGMTString();
    }
    document.cookie = name + "=" + value + expires + "; path=" + path;
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

Upvotes: 1

Related Questions