Wednesday, July 22, 2015

JavaScript and Cookie


JavaScript and Cookie
First we will see “how we can read cookie with JavaScript code?”
For that I have created one JavaScript function that will take one argument (name of cookie’s variable)

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;
}
Now in below code I will try to show how we can create cookies using JavaScript

function cookieCheck(){
        var interval;
            if(readCookie("userlogTime") == null)
                {
                    var cDateTime = new Date();
                     var timeSet = cDateTime.getHours();
                     document.cookie ="userlogTime="+timeSet;
                 }
         }

The above code show how we can create cookie using javascript

No comments:

Post a Comment