JQuery Cookies | Creating, Modifying and Expiring | Set and Unset Cookies


    Before going to learn on How to set/unset cookie with jQuery, we will see a small introduction on Cookies in Web world.
    
  A Cookie is a small piece of Information which is sent from a server of a website and is stored in web browser. whenever user browses the same website again server will identify his previous activity or information based on the Cooke stored on browser for that website and process the required details. Cookies can also be called as HTTP cookie, web cookie, or Internet cookie. Cookies can be used for Session management, Personalization, Tracking etc...

To create the cookies using JQuery, we have different plugins available. But now I am going to explain creating a Cookie with jQuery using plug-in jquery.cookie with jquery cookies example.

jquery.cookie is a simple, lightweight jQuery plugin for reading, writing and deleting cookies.
To get started, First you need to download it From Jquery cookies plugin download and add it after your jQuery library include as shown below.


Creating Cookies using JQuery


First thing we required to create a cookie is just add Name and Value of the cookie and store the cookie. Below Code shows simple way to create a cookie

$.cookie('name', 'value') 

In some scenarios we want to create a cookie for certain number of days and expire it automatically, in this case while creating cookie itself we can add one more attribute to tell when the cookie will expire. Example to expire a JQuery Cookie  shown below

$.cookie('name', 'value', { expires: 2 });

In above case cookie will be created and will Expire in 2 days.

In addition, we may want to create a cookie which is valid for the entire site. To make a cookie valid across entire site we need to add the Path attribute as shown below.

$.cookie('name', 'value', { expires: 2, path: '/' });

If we don't use path: '/' , then the cookie will be created with the Path of the page that created it.

Reading Cookies using JQuery


Now we will see how to read a cookie in different ways using jquery.cookie

To read a cookie simply use the cookie name which we created earlier as shown below

$.cookie('name'); //It will return the value of the cookie

If you read a cookie which is not created, then it will give undefined as the output
$.cookie('javaScriptFoo'); //It will return 'undefined' 

To read all the cookies we created, use simply cookie() without any name argument like below
$.cookie(); //It will return all the cookies available with { "name": "value" } pairs


Deleting Cookies using JQuery


Deleting a cookie is very simple. Just call the removeCookie() method with the cookie name as the argument, then the particular cookie will be deleted.

$.removeCookie('name'); // returns true as we created cookie with 'name' earlier.
$.removeCookie('JSfoo'); // returns false as we don't have any cookie with name 'JSfoo'


As per the note from jquery.cookie when deleting a cookie, you must pass the exact same path, domain and secure options that were used to set the cookie, unless you're relying on the default options that is. So make sure you remove the cookie the way you created . for example, If you created a cookie with Path as argument, then you need to delete it using path only as shown below

$.removeCookie('name',{ path: '/' });

Below are all the options available with JQuery cookie

expires : n           //expires in n days 
    path    : '/'        //The value of the path attribute of the cookie 
    domain  : 'abc.com'  //The value of the domain attribute of the cookie
    secure  : true        //If set to true the secure attribute of the cookie
                          //will be set and the cookie transmission will
                          //require a secure protocol (defaults to false).

Please share in comments, If you have any comments or need clarifications.





What is a CDN and How to load jQuery from CDN with Fallback?

What is a CDN ? 

CDN is an acronym for Content Delivery Network.
From wiki "A content delivery network or content distribution network (CDN) is a large distributed system of servers deployed in multiple data centers across the Internet. The goal of a CDN is to serve content to end-users with high availability and high performance."

As a developer  we mostly use CDNs for loading some JavaScript releated JS plugins and frame works like jQuery, Dojo, AngulaJS etc.. However CDN Not only used for downloading text/Script files but Its major use now a days is downloading objects like media files, software, documents etc.., applications like e-commerce, portals And also for live streaming media.

Which are the popular jQuery CDN ?

In this post we want to concentrate on jQuery related CDNs only so I ll be listing only jQuery related CDN sources mainly. You can use them in your application.

CDNs can offer a performance benefit by hosting jQuery on servers spread across the globe. This also offers an advantage that if the visitor to your webpage has already downloaded a copy of jQuery from the same CDN, it won't have to be re-downloaded.
Popular CDNs and their URLs

How to load jQuery locally when CDN fails?

There May be Situations where JavaScript file from CDN May not be loaded. There can be any reason for it as i mentioned it in my blog Here How to Check If JQuery Library Loaded?
WHat to do in this situation? Its simple just check If the jQuery library is loaded or not using This method and add the local JS file in Else condition as shown below.


That is it. Isn't it that simple???

How to Check If JQuery Plugin or Library is loaded?

There may be some situations where we need to know whether a JQuery plugin/library is loaded or not loaded.
For Example if we are using any CDN to load JQuery in our application and some times CDN may be blocked by the user or CDN Server is not reachable/down. So Its always better to check if jQury plugin is loaded or not once before using it.

To check if jQuery library is loaded?


to check if jQuery library and plugin is loaded?
to check if jQuery library and plugin is loaded?
to check if jQuery library
to check if jQuery library
if (typeof jQuery != 'undefined') {
     alert("jQuery library is loaded!");
 }

Or We can Check like below
 
if (jQuery) { 
   alert("jQuery library is loaded!");
}

Using Above methods we can Check If JQuery library is loaded r not. To Check If any particular jQuery plugin is loaded or not, we can use below method.

To check  if jQuery Plug-in is loaded?

if(jQuery().pluginMethod) {
    alert("jQuery Plugin is loaded!");
}

To check if validation plugin is loaded or not using JQuery.
 
if(jQuery().validate) {
    alert("Validation plugin exists");
    // Now I can use $('#someId').validate()
} 

We can also use jQuery isFunction() to determine if a there're a jQuery UI function.for Ex:- To Check if datepicker exists/ loaded or not

jQuery(document).ready(function() {
if (jQuery.isFunction(jQuery.fn.datepicker)) {
    console.log('datepicker Present')
}
});

JavaScript String slice, substring and substr Methods

JavaScript String holds the sequence of charters.
 var str = "This is Sample String"; 
To Extract portion of a String in javascript we have 3 methods avilable. They are
  • String.slice(start, end)
  • String.substring(start, end)
  • String.substr(start, length) 


String.slice()

This Method Extracts the part of a String and returns the extracted part as String.
It takes 2 arguments for start index and end index.
  • If we give negative arguments, String.slice method will extract the String from end position to start position
  • if we give single positive argument, then String.slice extracts the String from that position to the End of the String.
  • if we give single negative argument, then String.slice extracts the String from End of the String to those many characters specified in the argument.
  • If we Specify the out of index, It will return the empty String.

See below for Example of String.Slice behavior

 var str = "This is Sample String";
console.log("slice(8,14) : "+str.slice(8,14));
console.log("slice(-13,-7) : "+str.slice(-13,-7));
console.log("slice(8) : "+str.slice(8));
console.log("slice(-7) : "+str.slice(-7));
console.log("slice() : "+str.slice());
console.log("slice(50) : "+str.slice(50));


Output for Above :- 
 slice(8,14) : Sample
slice(-13,-7) : Sample
slice(8) : Sample String
slice(-7) :  String
slice() : This is Sample String
slice(50) :

String.substring()


JavaScript substring method is similar to slice, except behavior is different for negative argument.
Unlike Slice method which takes relative index from end of the String for negative arguments, substring method treats them from starting position of the String.
Say if i have a String str = "abc", and i am performaing str.substring(-3,-7), then Javascript will try to substring the str @ index between -13 and -7 and we don't have any characters at that indexes, it will return null.
However, If we use str.subgtring(-3), javaScript tries to return the SubString from -7 index to length of the String and we have String available from 0th Index, It will return the entire String.

 See below for Example of String.substring() behavior

var str = "This is Sample String";
console.log("substring(8,14) : "+str.substring(8,14));
console.log("substring(-13,-7) : "+str.substring(-13,-7));
console.log("substring(8) : "+str.substring(8));
console.log("substring(-7) : "+str.substring(-7));
console.log("substring() : "+str.substring());
console.log("substring(50) : "+str.substring(50));


 Output for Above :-
substring(8,14) : Sample
substring(-13,-7) :
substring(8) : Sample String
substring(-7) : This is Sample String
substring() : This is Sample String
substring(50) :


String.substr()


JavaScript substr method is similar to slice, except the second argument specifies the length of the string.
Also Behaviour of subStr() and Slice() methods changes based on the negative argument supplied.
If we pass only one argument and is negative to the subStr(), then it works similar like slice() method to from end of the String but it will return String with the length specified foe Ex:- str.subStr(-7) means it will return the String of 7 characters from End of the String str.
 If we pass 2 negative arguments to the substr() method, it will return the String from first argument position from end of the String to the lenght specified in second argument.

 See below for Example of String.substr() behavior for clear understanding.


var str = "This is Sample String";
console.log("substr(8,14) : "+str.substr(8,14));
console.log("substr(-11,7) : "+str.substr(-11,7));
console.log("substr(8) : "+str.substr(8));
console.log("substr(-7) : "+str.substr(-7));
console.log("substr() : "+str.substr());
console.log("substr(50) : "+str.substr(50));
 Output for Above :-
substr(8,14) : Sample String
substr(-11,7) : mple St
substr(8) : Sample String
substr(-7) :  String
substr() : This is Sample String
substr(50) :

From Above examples, we can conclude that If we want to perform operation based on indices, then we can go for slice() or subString() keeping in mind the behavior of the negative arguments. If we want to perform operation based on length then we go for substr().

For those who want to know the performance of these 3 methods here is a good jsperf comparison. http://jsperf.com/slice-vs-substr-vs-substring-methods-long-string/3