Search code examples
jquerycookiessetcookiejquery-cookie

jQuery Cookie doesn't save value


I have jQuery Cookie Plugin and want I to set a cookie (with expires) to execute a script after x pageviews but cookie doesnt return vlaue of pageviews but return NaN.

$(document).ready(function () {
    var visited = $.cookie('visited'); // visited = 0
    if (visited == 3) {
        execute script
    } 
    else {
        visited++;// increase counter of visits

        // set new cookie value to match visits
        var date = new Date();
        date.setTime(date.getTime() + (10 * 1000));
        $.cookie('visited', visited, {expires: date});

        return false;
    }
});

What is the problem in my script?


Solution

  • Try this:

    $(document).ready(function () {
    var visited = 0;
    if ($.cookie('visited')) {//test if cookie exist 
      visited = $.cookie('visited');
    }
    
        if (visited == 3) {
           //
        } 
        else {
            visited++;// increase counter of visits
    
            // set new cookie value to match visits
            var date = new Date();
            date.setTime(date.getTime() + (10 * 1000));
            $.cookie('visited', visited, {expires: 1});
    
            return false;
        }
    });
    

    https://jsfiddle.net/dfL94kjh/