Quackit Logo
HTML
CSS
Scripting
Database
Hosting
Design
XML
IMCreator - Free Website Builder

JavaScript Cookies

Cookies are small text files that sit on your hard disk. Cookies are created when you visit websites that use cookies to store information that they need (or prefer). Websites often use cookies to personalise the user experience - such as remembering your name (assuming you supplied it previously) or remembering the items in your shopping cart from previous visits.

Despite the many misconceptions about cookies being malicious, they are quite harmless. Cookies can't give your personal details to other websites, or transmit a virus or anything like that. A cookie can only be read by the server that created it. Websites normally use cookies to make its users' lives easier, not harder.

Creating Cookies in JavaScript

Code

Now check your cookies folder to see if the cookie was created. Alternatively, write code to read the cookie.

Note: If the cookie wasn't created, check the expiry date - it needs to be a date in the future.

You can update this value by using the same code with a different value. If you want to add a second value, simply use a different variable name (for example "myContents2=").

Reading Cookies in JavaScript

Code

You simply reference the cookie using document.cookie. The only problem with the above code is that it outputs the equals sign and everything before it (i.e. "myContents="). To stop this from happening, try the following code:

Code

Deleting Cookies in JavaScript

To delete a cookie, you can use the same code you used to create it but this time, set the expiry date in the past:

Code

Once you are comfortable with JavaScript and cookies, you can do things like use the getDate() function to set the date at a date in the future (say, 6 months), creating a function for setting and naming your cookies etc.

Enjoy this page?

  1. Link to this page (copy/paste into your own website or blog):
  2. Link to Quackit using one of these banner ads.

Thanks for supporting Quackit!