jQuery - Cookies

Wikitechy | 447 Views | jquery | 03 Jun 2016

 

  • Cookies are usually small text files, given in ID tags that are stored on your computer's browser directory or program data subfolders
  • Cookies are created when we use your browser to visit a website there by,
    • it is being used to keep track of our movements within the site, 
    • apart from this it helps us to resume where we left off, 
    • remembers our registered login, theme selection, preferences &
    •  other customization functions.
  • The website stores a corresponding file (with same ID tag) to the one they set in their browser and in this file they can track and keep information on your movements within the site and any information we may have voluntarily given while visiting the website, such as email address.
  • We can directly access the cookies by using this source code embed in your HTML
<script src="/path/to/js.cookie.js"></script>
  • We can download the cookies from this URL:

  https://github.com/js-cookie/js-cookie

Create a cookie, valid across the entire site :

Cookies.set('name', ‘Venkat from WikiTechy’);

Create a cookie that expires 7 days from now, valid across the entire site :

Cookies.set('name', ‘Venkat from WikiTechy’, { expires: 7 });

Create an expiring cookie, valid to the path of the current page :

Cookies.set('name', ‘Venkat from WikiTechy’, { expires: 7,  path: '' });

Read cookie :

Cookies.get('name'); // => ‘Venkat from WikiTechy’
Cookies.get('nothing'); // => undefined

Read all visible cookies :

Cookies.get(); // => { name: ‘Venkat from WikiTechy’ }

Delete cookie :

Cookies.remove('name');

Delete a cookie valid to the path of the current page :

Cookies.set('name', ‘Venkat from WikiTechy’, { path: '' });
Cookies.remove('name'); // fail!
Cookies.remove('name', { path: '' }); // removed!

Note :

When we delete a cookie, we must pass the exact same path and domain attributes that was used to set the cookie, unless you're relying on the default attributes.

Namespace conflicts :

  • In jquery the namespace Cookies, using no Conflict method will allow a user to define new namespace which will be mainly used to preserve the original one.
  • This is especially useful when running the script on third party sites e.g. as part of a widget or SDK.

JSON :

  • js-cookie provides unobtrusive JSON storage for cookies.
  • When creating a cookie, you can pass an Array or Object Literal instead of a string in the value. 
  • If we do so, js-cookie will store the string representation of the object according to JSON.stringify (JSON.stringify() method converts a JavaScript value to a JSON string)
Cookies.set('name', { foo: 'bar' });
  • When reading a cookie with the default Cookies.get api, we receive the string representation stored in the cookie:
Cookies.get('name'); // => '{"foo":"bar"}'
Cookies.get(); // => { name: '{"foo":"bar"}' }
  • When reading a cookie with the Cookies.getJSON api, we receive the parsed representation of the string stored in the cookie according to JSON.parse:
Cookies.getJSON('name'); // => { foo: 'bar' }
Cookies.getJSON(); // => { name: { foo: 'bar' } }

Sample Code :

<!DOCTYPE html> <html>     <head>         <title>             Wikitechy - get and set cookies         </title>             <script type="text/javascript"                 src="http://code.jquery.com/jquery.js">             </script>             <script src="js.cookie.js">             </script>             <script>                 $(document).ready(function(){                 $("#button1").click(function(){                 Cookies.set('name', 'Venkat from Wikitechy');                     // custom code to set the value as cookies                 var myvar = Cookies.get('name');                     // fetch the value for the cookie                 document.getElementById('output').innerHTML =myvar;                 });                 });             </script>     </head>         <body>             <button id="button1" >button1</button>             <p id="output">data change here</p>         </body> </html>

Code Explanation :

    Here we define the source the jQuery and set the script type as “text/javascript” which specifies the Internet media type (formerly known as MIME- Multi-Purpose Internet Mail Extensions type) of a script and source script reference URL.
    Here in this statement we have given the source file path as “js.cookie.js
    Here in this statement we have created a button” button1” using button element.
    The $(document).ready(function);  - specifies that the document to be fully loaded and ready before working with it, in order to prevent any jQuery code from running before the document is finished loading.

    $("button").click(function(){ - here is the button click event, which has been called here as element selector whose element “button” has been assigned for the click function.
    In this statement we have assigned the cookie name as “Venkat from wikitechy”.
    Now her we got the cookie value from the parameter “name” by using the get function whose value will be assigned for the variable “myvar”.
    Here we display the value of the id “output” whose paragraph element set has its value of the variable “myvar”.

Sample Output :


    Here we display the source java script cookie file where cookies store the value of the element when script is loading at the time and once after we perform any action, the value element will be fetched from the cookie.

    Here in this output we have shown the button ” button1” and <p> tag content "data change here” as shown above.

    Here in this output we have shown the button ”button1” just click on the button
    After that the text will be changed into “Venkat from wikitechy” as shown above.



Workshop

IOT Hackathon
Webinar

Join our Community

Advertise