Cookie in Javascript

Http protocol is stateless, so there is no native way to save some information between pages. But fortunately we have cookie in browsers.

First of all, how to check if browser supports cookie:

var isCookieEnabled = navigator.cookieEnabled;
alert(isCookieEnabled ? 'Cookie Enabled' : 'Cookie Disabled')

And when you checked that cookie works need to use the cookie storage. The easiest way is to use jQuery plugin for this jQuery Cookie Plugin

Just download archive:

Then put the script to your javascript’s folder in a project and add link to document. Head tag:

<script src="/path/to/jquery.cookie.js"></script>

And now it’s simple to get/set data directly in your script:

$.cookie('visited', 1); // set
alert($.cookie('visited')); // get

Total features see at github’s page

Books to read

Leave a Reply

Your email address will not be published. Required fields are marked *