Browser Cookie with JavaScript and jQuery

This short JavaScript article tutorial guides you how to work with browser cookie, cookie in JavaScript by using the JavaScript framework jQuery, through some basic missions: set JavaScript cookie and store data values into cookie; JavaScript read cookie, get stored values and use them for your web applications. A very helpful JavaScript tutorial for JavaScript beginners.


Sampled by © JavaScriptBank.com

Working with cookies using jQuery and JavaScript

Overview on using cookies via jQuery or JavaScript.

Today i want to go over a few techniques to easily use cookies via jQuery (much easier) or pure javascript.
What is a cookie?
A cookie is a text string that is included with Hypertext Transfer Protocol (HTTP) requests and responses. Cookies are used to maintain state information as you [...]

Overview on using cookies via jQuery or JavaScript.

Today i want to go over a few techniques to easily use cookies via jQuery (much easier) or pure javascript.

What is a cookie?

A cookie is a text string that is included with Hypertext Transfer Protocol (HTTP) requests and responses. Cookies are used to maintain state information as you navigate different pages on a Web site or return to the Web site at a later time. This article provides information about cookies.

What do i do with cookies

Cookies today can be seen used most often for storing user logged in information. That means that with cookies we can allow for our members to set a certain amount of time for their account to stay logged in. Also you use cookies to store very basic temporary information that the website collected from you at one point of time.

Cookies should NOT be used to store information that needs to be accessible by the user or by your website from a variety of places. By places i am referring to different machines and browsers that store the cookies locally.

How do i actually use them

Cookies are accessible by all web programming languages. That means, javascript, python, php, and many more. First i want to go over using cookies with jQuery since it is the easiest way to do this.

jQuery has a plugin you use with the jQuery library itself and you can really easily store and access your cookies. So lets look at the code of storing and displaying a cookie.

  1. <html>  
  2. <head>  
  3. <script src="http://code.jquery.com/jquery-latest.js"></script>  
  4. <script src="jquery.cookie.js"></script>  
  5. <script>  
  6. $(document).ready(function(){  
  7.     // set cookie  
  8.     $.cookie('my_cookie_name', 'value inside of it');  
  9.   
  10.     // get cookie  
  11.     alert($.cookie('my_cookie_name'));  
  12.   
  13.     // delete cookie  
  14.     $.cookie('my_cookie_name', null);  
  15. });  
  16. </script>  
  17. </head>  
  18. <body>  
  19. <a class="setme">Set Me</a>  
  20. <a class="tellme">Tell Me</a>  
  21. <a class="delete">DeleteM</a>  
  22. </body>  
  23. </html>  

Now let's go over the important parts of the code. First of course we embed jQuery itself, then we add the jquery cookie plugin and then we start our beautiful jQuery code.

The set cookie is pretty straight forward, one line of code that will set the cookie "my_cookie_name" with the value "value inside of it". We do that by passing in two parameters into our $.cookie() plugin. You do need the quotes around the name and the value of the cookie, feel free to use single or double quotes as your preference.

The get cookie code is even more straight forward we just pass in the cookie name in out jquery cookie plugin and it has the value we stored in there.

And finally deleting the cookie is almost the exact same as storing the cookie, only difference is we store null inside of it.

Now let's go more advanced

Now that we have set a cookie, added a value, and deleted the stored value it's time to do things like storing the cookie for a certain period of time, or to a certain date!

  1. // cookie expires in 10 days  
  2. $.cookie('cookie_name''our value', { path: '/', expires: 10 });  
  3.   
  4. // cookie expires in a set JavaScript Date  
  5. var date = new Date();  
  6. $.cookie('cookie_name''our value', { path: '/', expires: date });  

The first code sets a cookie to expire in 10 days. That's it... it's as simple as that. Pass in a third parameter that has the path to where you want to store the cookie in the browser directory, leaving this to / is your best choice. And then you set the expiration days.

The second code we first set a variable date to store the current date and then it will set the cookie to expire to the certain JavaScript date. Putting a real date in there will not work unless you stored a javascript date in a variable called date. Read more about JavaScript dates here.

How to do this with JavaScript

Here is the code to write a cookie with plain JavaScript

  1. function setCookie(key, value) {  
  2.    var expires = new Date();  
  3.    expires.setTime(expires.getTime() + 31536000000); //1 year  
  4.    document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();  
  5.    }  
  6.   
  7. function getCookie(key) {  
  8.    var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');  
  9.    return keyValue ? keyValue[2] : null;  
  10.    }  
  11.   
  12. setCookie('test''5');  
  13. alert(getCookie('test'));  

We set up two functions setCookie and getCookie. We need to pass in 2 variables into the setCookie the key and the value pair. Currenty the cookie is set to expire in a year but of course you can change that, i have the link on javscript dates above.

I hope i have shed some light on the world of cookies!

Language
Translate this page to English Translate this page to French Translate this page to Vietnamese

Recent articles
How to open a car sharing service
Vue developer as a vital part of every software team
Vue.js developers: hire them, use them and get ahead of the competition
3 Reasons Why Java is so Popular
Migrate to Angular: why and how you should do it
The Possible Working Methods of Python Ideology
JavaScript Research Paper: 6 Writing Tips to Craft a Masterpiece
Learning How to Make Use of New Marketing Trends
5 Important Elements of an E-commerce Website
How To Create A Successful Prototype For Your PCB


Top view articles
Top 10 Beautiful Christmas Countdown Timers
Adding JavaScript to WordPress Effectively with JavaScript Localization feature
65 Free JavaScript Photo Gallery Solutions
16 Free Code Syntax Highlighters by Javascript For Better Programming
Best Free Linux Web Programming Editors
Top 10 Best JavaScript eBooks that Beginners should Learn
Top 50 Most Addictive and Popular Facebook mini games
More 30 Excellent JavaScript/AJAX based Photo Galleries to Boost your Sites
Top 10 Free Web Chat box Plug-ins and Add-ons
The Ultimate JavaScript Tutorial in Web Design


Free JavaScript Tutorials & Articles
at www.JavaScriptBank.com