document.cookie="string of data & value separated by ; "We will start with a simple one line cookie without any expire date. Cookies are stored as name value pairs separated by semi columns ; . We will start with a simple example of storing a name in cookies.
document.cookie="name" + "=" + name; // name is a variable
Adding expire date or life of the cookiesWe will learn how to add expire date and time to the cookies. This is the life of the cookies in user computer after which cookies will be deleted. However if the user wishes they can remove cookies any point of time. If we are not adding any expire date to the cookies then the life of the cookies will last till the browser session only, once the browser is closed the cookies will be deleted. Here is the syntax to add expire date to our data.
document.cookie="name" + "=" + vlaue + ";expires="+dt.toUTCString();Here value is the data which we will store against name. dt is the date object and we are converting to Universal Standard by using toUTCString function.
This sample code will add cookies for one day. To do this we will add the user to enter its name. Then on submit we will execute a function. Inside this function we will create a date object., collect the date part by using getDate() and then set the new date by adding one day and using setDate function. Then we will store the cookie. Here is the code.
You can check this code in this DEMO of cookies