Showing posts with label jQuery For Beginners. Show all posts
Showing posts with label jQuery For Beginners. Show all posts

Tuesday, August 26, 2014

How to serialize ASP.NET web form using jQuery

In this post, find how to serialize ASP.NET web form using jQuery. jQuery provides a very useful function jQuery.serialize() which encodes a set of form elements as a string.

What is serialize and why do we need?


Serialize is a way to combine your form values and create a single string which then can be used to send to server for ajax request. It is useful when your form is huge and you need to post all the form input value to server using ajax. Creating such string manually is not desired. Serialize can help you with this.

Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked.

How to use it?


Consider a following form with 3 input controls with a submit button.
<form action="#" id="form1">
     First name: <input type="text" name="first name" /><br />
     Last name: <input type="text" name="last name" /><br />
     Email: <input type="text" name="email" /><br />
     <input type="submit" value="send" id="btnSubmit" />
</form>
So when we serialize this form, so following serialize string is returned using "$("#form1").serialize();"
"first+name=jQuery&last+name=byexample&email=jquerybyexample%40gmail.com"

You can easily include particular set of controls while serializing the form. For example, you want to include only input controls not select controls.
function SerializeForm()
{
   var sValue = $("#form1")
               .find("input")
               .serialize();
   return sValue ;
}
Above code will only serialize input controls only, ignoring all other controls.

What about ASP.NET Webform?


With ASP.NET Webform, there is an issue. As to maintain states between postback, ASP.NET adds two extra input controls with ID "__VIEWSTATE" and "__EVENTVALIDATION". And we don't want to serialize these two controls input. We need to ignore them otherwise your serialize string will break and code will fail. So use ".not()" selector to ignore these 2 controls.
function SerializeForm()
{
   var sValue = $("#form1")
               .find("input,textarea,select")
               .not("#__VIEWSTATE,#__EVENTVALIDATION")
               .serialize();
   return sValue ;
}
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, May 27, 2014

jQuery on() - Click event not working for dynamically added element

My colleague got stuck into a problem where he was using jQuery on() method to attach the click event handlers but click event was not working for dynamically added elements. Although he knew that .bind() method doesn't work for dynamically added element but he was quite sure about .live() and .on(). Since .live() method is already deprecated, so .on() method was the only left choice.

But for him even the .on() was working for one of his scenario. First let's see the scenario. There is a HTML table with set of rows and every row with class "trDummy" being added dynamically.
<table class="tbMain">
  <tr class="trDummy">
     <td>Some Data</td>
     <td><a href="#" class="toggle">Close</a></td>
  </tr>
</table>
And there was a close event attach to "tr" using .on() which does blah blah..
$(document).ready(function () {
  $('.trDummy').on('click', '.close', function () {
     //Do something...
  });
});
The close event was working fine for already added "tr" but it was not working for dynamically added "tr" rows. Is there anything wrong?
YES, there is. Official jQuery document about jQuery on() says,

" Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()."

So click event works only for element present on the page. If it is added dynamically, it's not going to work. So, the solution is to delegate the events to that wrapper, instead of binding handlers directly on the dynamic elements. So always use static elements in which you add the dynamic control while using .on().
$(document).ready(function () {
  $('.tbMain').on('click', '.close', function () {
     //Do something...
  });
});
Related Post: Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, October 1, 2013

jQuery code not working - A Daily Battle

Developers life is full of various code battles and "jQuery is not working" or "jQuery code is not working" is a just another daily battle which they have to fight against while working with jQuery. The message "jQuery is not working" itself defines its pain saying "Oh!!! there is something buggy in your code and that is stopping me from working". So in this post, we will see some basic strategies to win this "Daily Battle".


Earlier I had posted about Common jQuery Mistakes, Various reasons and solutions of jQuery is not defined error and series of articles on jQuery Mobile which you may find helpful to read.. Okay, Lets begin...

STRATEGY No. 1 : Check for jQuery Reference

The first strategy is to ensure that you have included the reference of jQuery library and That too at correct place. It has to before your jQuery code.
<script type="text/javascript" language="javascript">
  $(document).ready(function() {
      //Your jQuery code goes here....
 });
</script>

<script type="text/javascript" src="Script/jquery-1.9.2.min.js"></script>
So with this code, you are ready for your "Daily Battle", as the reference of the jQuery library is after the code.

Another important thing which matters a lot is order of your scripts. For example, if you are using jQuery along with jQuery UI, first include jQuery and then jQuery UI library.
<script type="text/javascript" src="Script/jquery-1.9.2.min.js"></script>
<script type="text/javascript" src="Script/jquery-ui-1.8.18.min.js"></script>
Same is true while using jQuery plugins.

STRATEGY No. 2 : Check Your Selectors

The second strategy is to find out whether "Wrong Element ID or CSS Class Name" is not used. This is a very common mistake developers do while writing code. This happens because developers believe that they can never go run with this. As they say "Confidence is good but over-confidence is bad".

Another common cause is to mix up "#" (hash) and "." (dot). Remember, "#" is used to select elements by ID and "." is used to select elements by css class name. Many times developer mixes these two and get ready for "Daily Battle". So make sure that your selectors are correct.

STRATEGY No. 3 : Check for Comma, Semi-colon, Brackets and Syntax

When you write jQuery code, you will find comma, quotes, semi-colon and brackets everywhere. Without the proper/correct use of these characters, your jQuery code is not going to love you back. So make sure that all these character are in place.

Another common mistake which every developer does, not intentionally though is incorrect syntax. Sometimes due to hurry or time limit, developers may ignore to check syntax which may lead to "Daily Battle". So make sure your syntax is correct.

STRATEGY No. 4 : Check for jQuery Version

jQuery team is continuously updating this library for making things fast and include new things. And they come up with newer version. Due to excitement of new release and eagerness to use new functionality, developers sometime include the new jQuery version without checking for old code compatibility.

For example, $.browser property to check for browser was removed in jQuery 1.9. And if you are using $.browser in your code and you have updated your code to jQuery 1.9, then your old code is going to break. Your Lead/ Project Manger/ Client will give you a kick and you are ready for your "Daily Battle".

So before updating to newer/latest version, check the release log on jQuery website to find out if any functionality is removed or deprecated in newer release. And always remember to test your old code against the new release.

STRATEGY No. 5 : Check for Conflict

Conflict happens. It happens everywhere. Well, lets admit it that "Nobody likes Conflict" and same is true for jQuery. It also hates conflicts. But conflicts with whom? Well, remember jQuery is not the ONLY client side library which exists in this world. There are many other competitors like prototype, mootools, YUI etc. And when there is competition, there is conflict of interest.

These libraries also use $() as their global function and to define variables. This situation creates conflict as $() is used by jQuery and other libraries as their global function. And you are ready for your "Daily Battle".

So we need conflict resolution. And to resolve conflict, jQuery has jQuery.noConflict().
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
     jQuery.noConflict();
     // Use jQuery via jQuery(...)
     jQuery(document).ready(function(){
       jQuery("div").hide();
     });  
     // Use Prototype with $(...), etc.
     $('someid').hide();
</script>

The above mentioned strategies are nothing, but just a checklist which you can always follow when your "jQuery code is not working". If you have anything to add in this, please include them in comments and share with the world.

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, August 13, 2013

Using jQuery with ASP.NET

As this post is about "using jQuery with ASP.NET" so we will not be looking into "What is jQuery" and "How to use jQuery" assuming you know basics of jQuery. If not, then please read "Learn how to use jQuery?"

To begin with using jQuery with ASP.NET, first download the latest version the jQuery library from jQuery website and unzip or copy the file in your project or Visual studio solution. Microsoft Visual studio 2010 and 2012 include jQuery by default and provide intellisense to use jQuery. Assuming that you have placed the library in Script folder, add this in the head of your ASP.NET page (simple or master). (Its a good practice to keep your all js file under Script folder).
<script src="Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
Or you can directly refer them using various CDNs. Put this line of code in head section of ASP.NET Page.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
In the above code, I have not used "http" protocol while referencing jQuery from Google CDN. Its not a mistake rather always use protocol less URL for referencing jQuery.

After this setup, you can use jQuery in your ASP.NET page. Let's see a demo.

Show alert window on click of ASP.NET Button.

Assuming a ASP.NET button with ID "btnSubmit " is placed on the page.
<asp:Button ID="btnSubmit" runat="server" Text="Button" />
And now bind the click event to ASP.NET Button in document.ready section.
<script type="text/javascript">
  $(document).ready(function() {
    $("#btnSubmit").click(function() {
         alert("Alert using jQuery");
    });
  });
</script>
In above jQuery code block, we have attached click event to the button using ID selectors. Read more about other jQuery selectors and how to use them.

Below is a list of useful jQuery code example for ASP.NET controls that we use on daily basis. One thing, while creating object of any ASP.NET control, always use ClientID. As when Master pages are used then the ID of the ASP.NET controls is changed at run time. Read more here. But with ASP.NET 4.0, this is changed and now you have control over the Client ID using ClientIDMode property.

Get label value:
$('#<%=Label1.ClientID%>').text();
Set label value:
$('#<%=Label1.ClientID%>').text("New Value");
Get Textbox value:
$('#<%=TextBox1.ClientID%>').val();
Set Textbox value:
$('#<%=TextBox1.ClientID%>').val("New Value");
Get Dropdown value:
$('#<%=DropDownList1.ClientID%>').val();
Set Dropdown value:
$('#<%=DropDownList1.ClientID%>').val("New Value");
Get text of selected item in dropdown:
$('#<%=DropDownList1.ClientID%> option:selected').text();
Get Checkbox Status:
$('#<%=CheckBox1.ClientID%>').attr('checked');
Check the Checkbox:
$('#<%=CheckBox1.ClientID%>').attr('checked',true);
Uncheck the Checkbox:
$('#<%=CheckBox1.ClientID%>').attr('checked',false);
Get Radiobutton Status:
$('#<%=RadioButton1.ClientID%>').attr('checked');
Check the RadioButton:
$('#<%=RadioButton1.ClientID%>').attr('checked',true);
Uncheck the RadioButton:
$('#<%=RadioButton1.ClientID%>').attr('checked',false);
Disable any control:
$('#<%=TextBox1.ClientID%>').attr('disabled', true);
Enable any control:
$('#<%=TextBox1.ClientID%>').attr('disabled', false);
Make textbox read only:
$('#<%=TextBox1.ClientID%>').attr('readonly', 'readonly');
I had already posted many ASP.NET related post and below you find links some useful posts.

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Thursday, July 25, 2013

Difference Between jQuery().each() and jQuery.each()

jQuery has 2 different methods jQuery().each() (Also written as "$.each()") and jQuery.each(). Both the methods are similar in nature used for iteration or looping but the differ only at the level where they are used.

jQuery.each(): is used to iterate, exclusively, over a jQuery object. When called it iterates over the DOM elements that are part of the jQuery object.

$.each(): function can be used to iterate over any collection, whether it is an object or an array.

Related Post:
First, let see how jQuery.each() works. To work with this function, you always need to pass a selector on which iteration needs to be performed. Consider the following HTML,
<ul>
    <li>foo</li>
    <li>bar</li>
</ul>
Now below jQuery code, will select all "li" elements and loop through each of the item and logs its index and text.
$( "li" ).each(function( index ) {
  console.log( index + ": " + $(this).text() );
});
On the other side, $.each() is used to iterate through an object or array collection. See below jQuery code.
var obj = { one:1, two:2, three:3, four:4, five:5 };
$.each( obj, function( key, value ) {
  alert( key + ": " + value );
});
Got the idea about the difference. But you can also make $.each() function to make it similar to jQuery.each(). All you need to do is to instead of object or array, you can pass DOM collection to achieve the same result. See below jQuery code.
$.each($( "li" ), function( index, value ) {
  console.log( index + ": " + $(this).text() );
});
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, July 9, 2013

Latest jQuery interview questions and answers

Below is the list of latest and updated jQuery interview questions and their answers for freshers as well as experienced users. These interview question covers latest version of jQuery which is jQuery 2.0. These interview questions will help you to prepare for the interviews, quick revision and provide strength to your technical skills.


Q1. What is jQuery?
Ans: jQuery is fast, lightweight and feature-rich client side JavaScript Library/Framework which helps in to traverse HTML DOM, make animations, add Ajax interaction, manipulate the page content, change the style and provide cool UI effect. It is one of the most popular client side library and as per a survey it runs on every second website.

Q2. Why do we use jQuery?
Ans: Due to following advantages.
  • Easy to use and learn.
  • Easily expandable.
  • Cross-browser support (IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+)
  • Easy to use for DOM manipulation and traversal.
  • Large pool of built in methods.
  • AJAX Capabilities.
  • Methods for changing or applying CSS, creating animations.
  • Event detection and handling.
  • Tons of plug-ins for all kind of needs.

Q3. How JavaScript and jQuery are different?
Ans: JavaScript is a language While jQuery is a library built in the JavaScript language that helps to use the JavaScript language.

Q4. Is jQuery replacement of Java Script?
Ans: No. jQuery is not a replacement of JavaScript. jQuery is a different library which is written on top of JavaScript. jQuery is a lightweight JavaScript library that emphasizes interaction between JavaScript and HTML.

Q5. Is jQuery a library for client scripting or server scripting?
Ans. Client side scripting.

Q6. Does jQuery follow W3C recommendations?
Ans: No.

Q7. What is the basic need to start with jQuery?
Ans: To start with jQuery, one need to make reference of it's library. The latest version of jQuery can be downloaded from jQuery.com.

Q8. Which is the starting point of code execution in jQuery?
Ans: The starting point of jQuery code execution is $(document).ready() function which is executed when DOM is loaded.

Q9. What does dollar sign ($) means in jQuery?
Ans: Dollar Sign is nothing but it's an alias for JQuery. Take a look at below jQuery code.
$(document).ready(function(){
});
Over here $ sign can be replaced with "jQuery" keyword.
jQuery(document).ready(function(){
});
Q10. Can we have multiple document.ready() function on the same page?
Ans: YES. We can have any number of document.ready() function on the same page.

Q11. Can we use our own specific character in the place of $ sign in jQuery?
Ans: Yes. It is possible using jQuery.noConflict().

Q12. Is it possible to use other client side libraries like MooTools, Prototype along with jQuery?
Ans: Yes.

Q13. What is jQuery.noConflict?
Ans: As other client side libraries like MooTools, Prototype can be used with jQuery and they also use $() as their global function and to define variables. This situation creates conflict as $() is used by jQuery and other library as their global function. To overcome from such situations, jQuery has introduced jQuery.noConflict().
jQuery.noConflict();
// Use jQuery via jQuery(...)
jQuery(document).ready(function(){
   jQuery("div").hide();
});  
You can also use your own specific character in the place of $ sign in jQuery.
var $j = jQuery.noConflict();
// Use jQuery via jQuery(...)
$j(document).ready(function(){
   $j("div").hide();
});  
Q14. Is there any difference between body onload() and document.ready() function?
Ans: document.ready() function is different from body onload() function for 2 reasons.
  1. We can have more than one document.ready() function in a page where we can have only one body onload function.
  2. document.ready() function is called as soon as DOM is loaded where body.onload() function is called when everything gets loaded on the page that includes DOM, images and all associated resources of the page.

Q15. What is the difference between .js and .min.js?
Ans: jQuery library comes in 2 different versions Production and Deployment. The deployment version is also known as minified version. So .min.js is basically the minified version of jQuery library file. Both the files are same as far as functionality is concerned. but .min.js is quite small in size so it loads quickly and saves bandwidth.

Q16. Why there are two different version of jQuery library?
Ans: jQuery library comes in 2 different versions.
  1. Production
  2. Deployment
The production version is quite useful at development time as jQuery is open source and if you want to change something then you can make those changes in production version. But the deployment version is minified version or compressed version so it is impossible to make changes in it. Because it is compressed, so its size is very less than the production version which affects the page load time.

Q17. What is a CDN?
Ans: 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.

Q18. Which are the popular jQuery CDN? and what is the advantage of using CDN?
Ans: There are 3 popular jQuery CDNs.
  1. 1. Google.
  2. 2. Microsoft
  3. 3. jQuery.
Advantage of using CDN.
  • It reduces the load from your server.
  • It saves bandwidth. jQuery framework will load faster from these CDN.
  • The most important benefit is it will be cached, if the user has visited any site which is using jQuery framework from any of these CDN

Q19. How to load jQuery from CDN?
Ans: Below is the code to load jQuery from all 3 CDNs.
Code to load jQuery Framework from Google CDN
<script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
Code to load jQuery Framework from Microsoft CDN
<script type="text/javascript"
    src="http://ajax.microsoft.com/ajax/jquery/jquery-1.9.1.min.js">
</script>
Code to load jQuery Framework from jQuery Site(EdgeCast CDN)
<script type="text/javascript"
    src="http://code.jquery.com/jquery-1.9.1.min.js">
</script>
Q20. How to load jQuery locally when CDN fails?
Ans: It is a good approach to always use CDN but sometimes what if the CDN is down (rare possibility though) but you never know in this world as anything can happen.

Below given jQuery code checks whether jQuery is loaded from Google CDN or not, if not then it references the jQuery.js file from your folder.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined')
{
  document.write(unescape("%3Cscript src='Scripts/jquery.1.9.1.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>
It first loads the jQuery from Google CDN and then check the jQuery object. If jQuery is not loaded successfully then it will references the jQuery.js file from hard drive location. In this example, the jQuery.js is loaded from Scripts folder.

Q21. What are selectors in jQuery and how many types of selectors are there?
Ans: To work with an element on the web page, first we need to find them. To find the html element in jQuery we use selectors. There are many types of selectors but basic selectors are:

  • Name: Selects all elements which match with the given element Name.
  • #ID: Selects a single element which matches with the given ID
  • .Class: Selects all elements which match with the given Class.
  • Universal (*): Selects all elements available in a DOM.
  • Multiple Elements E, F, G: Selects the combined results of all the specified selectors E, F or G.
  • Attribute Selector: Select elements based on its attribute value.

Q22. How do you select element by ID in jQuery?
Ans: To select element use ID selector. We need to prefix the id with "#" (hash symbol). For example, to select element with ID "txtName", then syntax would be,
$('#txtName')
Q23. What does $("div") will select?
Ans: This will select all the div elements on page.

Q24. How to select element having a particular class (".selected")?
Ans: $('.selected'). This selector is known as class selector. We need to prefix the class name with "." (dot).

Q25. What does $("div.parent") will select?
Ans: All the div element with parent class.

Q26. What are the fastest selectors in jQuery?
Ans: ID and element selectors are the fastest selectors in jQuery.

Q27. What are the slow selectors in jQuery?
Ans: class selectors are the slow compare to ID and element.

Q28. How jQuery selectors are executed?
Ans: Your last selectors is always executed first. For example, in below jQuery code, jQuery will first find all the elements with class ".myCssClass" and after that it will reject all the other elements which are not in "p#elmID".
$("p#elmID .myCssClass");
Q29. Which is fast document.getElementByID('txtName') or $('#txtName').?
Ans: Native JavaScipt is always fast. jQuery method to select txtName "$('#txtName')" will internally makes a call to document.getElementByID('txtName'). As jQuery is written on top of JavaScript and it internally uses JavaScript only So JavaScript is always fast.

Q30. Difference between $(this) and 'this' in jQuery?
Ans: this and $(this) refers to the same element. The only difference is the way they are used. 'this' is used in traditional sense, when 'this' is wrapped in $() then it becomes a jQuery object and you are able to use the power of jQuery.
$(document).ready(function(){
    $('#spnValue').mouseover(function(){
       alert($(this).text());
  });
});
In below example, this is an object but since it is not wrapped in $(), we can't use jQuery method and use the native JavaScript to get the value of span element.
$(document).ready(function(){
    $('#spnValue').mouseover(function(){
       alert(this.innerText);
  });
});
Q31. How do you check if an element is empty?
Ans: There are 2 ways to check if element is empty or not. We can check using ":empty" selector.
$(document).ready(function(){
    if ($('#element').is(':empty')){
       //Element is empty
  }
});
And the second way is using the "$.trim()" method.
$(document).ready(function(){
     if($.trim($('#element').html())=='') {
       //Element is empty
  }
});
Q32. How do you check if an element exists or not in jQuery?
Ans: Using jQuery length property, we can ensure whether element exists or not.
$(document).ready(function(){
    if ($('#element').length > 0){
       //Element exists
  });
});
Q33. What is the use of jquery .each() function?
Ans: The $.each() function is used to iterate over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is an object or an array.

Q34. What is the difference between jquery.size() and jquery.length?
Ans: jQuery .size() method returns number of element in the object. But it is not preferred to use the size() method as jQuery provide .length property and which does the same thing. But the .length property is preferred because it does not have the overhead of a function call.

Q35. What is the difference between $('div') and $('<div/>') in jQuery?
Ans: $('<div/>') : This creates a new div element. However this is not added to DOM tree unless you don't append it to any DOM element.

$('div') : This selects all the div element present on the page.

Q36. What is the difference between parent() and parents() methods in jQuery?
Ans: The basic difference is the parent() function travels only one level in the DOM tree, where parents() function search through the whole DOM tree.

Q37. What is the difference between eq() and get() methods in jQuery?
Ans: eq() returns the element as a jQuery object. This method constructs a new jQuery object from one element within that set and returns it. That means that you can use jQuery functions on it.

get() return a DOM element. The method retrieve the DOM elements matched by the jQuery object. But as it is a DOM element and it is not a jQuery-wrapped object. So jQuery functions can't be used. Find out more here.

Q38. How do you implement animation functionality?
Ans: The .animate() method allows us to create animation effects on any numeric CSS property. This method changes an element from one state to another with CSS styles. The CSS property value is changed gradually, to create an animated effect.

Syntax is:
(selector).animate({styles},speed,easing,callback)
  • styles: Specifies one or more CSS properties/values to animate.
  • duration: Optional. Specifies the speed of the animation.
  • easing: Optional. Specifies the speed of the element in different points of the animation. Default value is "swing".
  • callback: Optional. A function to be executed after the animation completes.
Simple use of animate function is,
$("btnClick").click(function(){
  $("#dvBox").animate({height:"100px"});
});
Q39. How to disable jQuery animation?
Ans: Using jQuery property "jQuery.fx.off", which when set to true, disables all the jQuery animation. When this is done, all animation methods will immediately set elements to their final state when called, rather than displaying an effect.

Q40. How do you stop the currently-running animation?
Ans: Using jQuery ".stop()" method.

Q41. What is the difference between .empty(), .remove() and .detach() methods in jQuery?
Ans: All these methods .empty(), .remove() and .detach() are used for removing elements from DOM but they all are different.

.empty(): This method removes all the child element of the matched element where remove() method removes set of matched elements from DOM.

.remove(): Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

.detach(): This method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.

Find out more here

Q42. Explain .bind() vs .live() vs .delegate() vs .on()
Ans: All these 4 jQuery methods are used for attaching events to selectors or elements. But they all are different from each other.

.bind(): This is the easiest and quick method to bind events. But the issue with bind() is that it doesn't work for elements added dynamically that matches the same selector. bind() only attach events to the current elements not future element. Above that it also has performance issues when dealing with a large selection.

.live(): This method overcomes the disadvantage of bind(). It works for dynamically added elements or future elements. Because of its poor performance on large pages, this method is deprecated as of jQuery 1.7 and you should stop using it. Chaining is not properly supported using this method.

.delegate(): The .delegate() method behaves in a similar fashion to the .live() method, but instead of attaching the selector/event information to the document, you can choose where it is anchored and it also supports chaining.

.on(): Since live was deprecated with 1.7, so new method was introduced named ".on()". This method provides all the goodness of previous 3 methods and it brings uniformity for attaching event handlers.

Find out more here

Q43. What is wrong with this code line "$('#myid.3').text('blah blah!!!');"
Ans: The problem with above statement is that the selectors is having meta characters and to use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\\.bar").
So the correct syntax is,
$('#myid\\.3').text('blah blah!!!');

Q44. How to create clone of any object using jQuery?
Ans: jQuery provides clone() method which performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes.
$(document).ready(function(){
  $('#btnClone').click(function(){
     $('#dvText').clone().appendTo('body');
     return false;
  });
});
Q45. Does events are also copied when you clone any element in jQuery?
Ans: As explained in previous question, using clone() method, we can create clone of any element but the default implementation of the clone() method doesn't copy events unless you tell the clone() method to copy the events. The clone() method takes a parameter, if you pass true then it will copy the events as well.
$(document).ready(function(){
   $("#btnClone").bind('click', function(){
     $('#dvClickme').clone(true).appendTo('body');
  });
Q46. What is difference between prop and attr?
Ans: attr(): Get the value of an attribute for the first element in the set of matched elements. Whereas,.prop(): (Introduced in jQuery 1.6) Get the value of a property for the first element in the set of matched elements.

Attributes carry additional information about an HTML element and come in name="value" pairs. Where Property is a representation of an attribute in the HTML DOM tree. once the browser parse your HTML code ,corresponding DOM node will be created which is an object thus having properties.

attr() gives you the value of element as it was defines in the html on page load. It is always recommended to use prop() to get values of elements which is modified via javascript/jquery , as it gives you the original value of an element's current state. Find out more here.

Q47. What is event.PreventDefault?
Ans: The event.preventDefault() method stops the default action of an element from happening. For example, Prevents a link from following the URL.

Q48. What is the difference between event.PreventDefault and event.stopPropagation?
Ans: event.preventDefault(): Stops the default action of an element from happening.
event.stopPropagation(): Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. For example, if there is a link with a click method attached inside of a DIV or FORM that also has a click method attached, it will prevent the DIV or FORM click method from firing.

Q49. What is the difference between event.PreventDefault and "return false"?
Ans: e.preventDefault() will prevent the default event from occurring, e.stopPropagation() will prevent the event from bubbling up and return false will do both.

Q50. What is the difference between event.stopPropagation and event.stopImmediatePropagation?
Ans: event.stopPropagation() allows other handlers on the same element to be executed, while event.stopImmediatePropagation() prevents every event from running. For example, see below jQuery code block.
$("p").click(function(event){
  event.stopImmediatePropagation();
});
$("p").click(function(event){
  // This function won't be executed
  $(this).css("background-color", "#f00");
}); 
If event.stopPropagation was used in previous example, then the next click event on p element which changes the css will fire, but in case event.stopImmediatePropagation(), the next p click event will not fire.

Q51. How to check if number is numeric while using jQuery 1.7+?
Ans: Using "isNumeric()" function which was introduced with jQuery 1.7.

Q52. How to check data type of any variable in jQuery?
Ans: Using $.type(Object) which returns the built-in JavaScript type for the object.

Q53. How do you attach a event to element which should be executed only once?
Ans: Using jQuery one() method. This attaches a handler to an event for the element. The handler is executed at most once per element. In simple terms, the attached function will be called only once.
$(document).ready(function() {
    $("#btnDummy").one("click", function() {
        alert("This will be displayed only once.");
    });
});​
Q54. Can you include multiple version of jQuery? If yes, then how they are executed?
Ans: Yes. Multiple versions of jQuery can be included in same page.

Q55. In what situation you would use multiple version of jQuery and how would you include them?
Ans: Well, it is quite possible that the jQuery plugins which are used are dependent on older version but for your own jQuery code, you would like to use newer version. So because of this dependency, multiple version of jQuery may required sometimes on single page.

Below code shows how to include multiple version of jQuery.
<script type='text/javascript' src='js/jquery_1.9.1.min.js'></script>

<script type='text/javascript'>
 var $jq = jQuery.noConflict();
</script>

<script type='text/javascript' src='js/jquery_1.7.2.min.js'></script>
By this way, for your own jQuery code use "$jq", instead of "$" as "$jq" refers to jQuery 1.9.1, where "$" refers to 1.7.2.

Q56. Is it possible to hold or delay document.ready execution for sometime?
Ans: Yes, its possible. With Release of jQuery 1.6, a new method "jQuery.holdReady(hold)" was introduced. This method allows to delay the execution of document.ready() event. document.ready() event is called as soon as your DOM is ready but sometimes there is a situation when you want to load additional JavaScript or some plugins which you have referenced.
​
$.holdReady(true);
$.getScript("myplugin.js", function() {
     $.holdReady(false);
});
Q57. What is chaining in jQuery?
Ans: Chaining is one of the most powerful feature of jQuery. In jQuery, Chaining means to connect multiple functions, events on selectors. It makes your code short and easy to manage and it gives better performance. The chain starts from left to right. So left most will be called first and so on.
​$(document).ready(function(){
    $('#dvContent').addClass('dummy');
    $('#dvContent').css('color', 'red');
    $('#dvContent').fadeIn('slow');
});​
The above jQuery code sample can be re-written using chaining. See below.
​$(document).ready(function(){
    $('#dvContent').addClass('dummy')
          .css('color', 'red')
          .fadeIn('slow');     
});​
Not only functions or methods, chaining also works with events in jQuery.

Q58. How does caching helps and how to use caching in jQuery?
Ans: Caching is an area which can give you awesome performance, if used properly and at the right place. While using jQuery, you should also think about caching. For example, if you are using any element in jQuery more than one time, then you must cache it. See below code.
$("#myID").css("color", "red");
//Doing some other stuff......
$("#myID").text("Error occurred!");
​
Now in above jQuery code, the element with #myID is used twice but without caching. So both the times jQuery had to traverse through DOM and get the element. But if you have saved this in a variable then you just need to reference the variable. So the better way would be,
var $myElement = $("#myID").css("color", "red");
//Doing some other stuff......
$myElement.text("Error occurred!");
​
So now in this case, jQuery won't need to traverse through the whole DOM tree when it is used second time. So in jQuery, Caching is like saving the jQuery selector in a variable. And using the variable reference when required instead of searching through DOM again.

Q59. You get "jquery is not defined" or "$ is not defined" error. What could be the reason?
Ans: There could be many reasons for this.
  • You have forgot to include the reference of jQuery library and trying to access jQuery.
  • You have include the reference of the jQuery file, but it is after your jQuery code.
  • The order of the scripts is not correct. For example, if you are using any jQuery plugin and you have placed the reference of the plugin js before the jQuery library then you will face this error.

Q60. How to write browser specific code using jQuery?
Ans: Using jQuery.browser property, we can write browser specific code. This property contains flags for the useragent, read from navigator.userAgent. This property was removed in jQuery 1.9.

Q61. Can we use jQuery to make ajax request?
Ans: Yes. jQuery can be used for making ajax request.

Q62. What are various methods to make ajax request in jQuery?
Ans: Using below jQuery methods, you can make ajax calls.
  • load() : Load a piece of html into a container DOM
  • $.getJSON(): Load JSON with GET method.
  • $.getScript(): Load a JavaScript file.
  • $.get(): Use to make a GET call and play extensively with the response.
  • $.post(): Use to make a POST call and don't want to load the response to some container DOM.
  • $.ajax(): Use this to do something on XHR failures, or to specify ajax options (e.g. cache: true) on the fly.
Find out more here.

Q63. Is there any advantage of using $.ajax() for ajax call against $.get() or $.post()?
Ans: By using jQuery post()/ jQuery get(), you always trust the response from the server and you believe it is going to be successful all the time. Well, it is certainly not a good idea to trust the response. As there can be n number of reason which may lead to failure of response.

Where jQuery.ajax() is jQuery's low-level AJAX implementation. $.get and $.post are higher-level abstractions that are often easier to understand and use, but don't offer as much functionality (such as error callbacks). Find out more here.

Q64. What are deferred and promise object in jQuery?
Ans: Deferred and promise are part of jQuery since version 1.5 and they help in handling asynchronous functions like Ajax. Find out more here.

Q65. Can we execute/run multiple Ajax request simultaneously in jQuery? If yes, then how?
Ans: Yes, it is possible to execute multiple Ajax request simultaneously or in parallel. Instead of waiting for first ajax request to complete and then issue the second request is time consuming. The better approach to speed up things would be to execute multiple ajax request simultaneously.

Using jQuery .when() method which provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events. Find out more here.

Q66. Can you call C# code-behind method using jQuery? If yes,then how?
Ans: Yes. We can call C# code-behind function via $.ajax. But for do that it is compulsory to mark the method as WebMethod.

Q67. Which is the latest version of jQuery library?
Ans: The latest version (when this post is written) of jQuery is 1.10.2 or 2.0.3. jQuery 2.x has the same API as jQuery 1.x, but does not support Internet Explorer 6, 7, or 8.

Q68. Does jQuery 2.0 supports IE?
Ans: No. jQuery 2.0 has no support for IE 6, IE 7 and IE 8.

Q69. What are source maps in jQuery?
Ans: In case of jQuery, Source Map is nothing but mapping of minified version of jQuery against the un-minified version. Source map allows to debug minified version of jQuery library. Source map feature was release with jQuery 1.9. Find out more here.

Q70. How to use migrate jQuery plugin?
Ans: with release of 1.9 version of jQuery, many deprecated methods were discarded and they are no longer available. But there are many sites in production which are still using these deprecated features and it's not possible to replace them overnight. So jQuery team provided with jQuery Migrate plugin that makes code written prior to 1.9 work with it.

So to use old/deprecated features, all you need to do is to provide reference of jQuery Migrate Plugin. Find out more here.

Q71. Is it possible to get value of multiple CSS properties in single statement?
Ans: Well, before jQuery 1.9 release it was not possible but one of the new feature of jQuery 1.9 was .css() multi-property getter.
var propCollection = $("#dvBox").css([ "width", "height", "backgroundColor" ]);
In this case, the propCollection will be an array and it will look something like this.
{ 
  width: "100px", 
  height: "200px", 
  backgroundColor: "#FF00FF" 
}
Q72. How do you stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements?
Ans: It can be done via calling .stop([clearQueue ] [, jumpToEnd ]) method and by passing both the parameters as true.

Q73. What is finish method in jQuery?
Ans: The .finish() method stops all queued animations and places the element(s) in their final state. This method was introduced in jQuery 1.9.

Q74. What is the difference between calling stop(true,true) and finish method?
Ans: The .finish() method is similar to .stop(true, true) in that it clears the queue and the current animation jumps to its end value. It differs, however, in that .finish() also causes the CSS property of all queued animations to jump to their end values, as well.

Q75. Consider a scenario where things can be done easily with javascript, would you still prefer jQuery?
Ans: No. If things can be done easily via CSS or JavaScript then You should not think about jQuery. Remember, jQuery library always comes with xx kilobyte size and there is no point of wasting bandwidth.

Q76. Can we use protocol less URL while referencing jQuery from CDNs?
Ans: Yes. Below code is completely valid.
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>
Q77. What is the advantage of using protocol less URL while referencing jQuery from CDNs?
Ans: It is quite useful when you are moving from HTTP to HTTPS url. You need to make sure that correct protocol is used for referencing jQuery library as pages served via SSL should contain no references to content served through unencrypted connections.

"protocol-less" URL is the best way to reference third party content that’s available via both HTTP and HTTPS. When a URL’s protocol is omitted, the browser uses the underlying document’s protocol instead. Find out more here.

Q78. What is jQuery plugin and what is the advantage of using plugin?
Ans: A plug-in is piece of code written in a standard JavaScript file. These files provide useful jQuery methods which can be used along with jQuery library methods. jQuery plugins are quite useful as its piece of code which is already written by someone and re-usable, which saves your development time.

Q79. What is jQuery UI?
Ans: jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library that can be used to build interactive web applications.

Q80. What is the difference between jQuery and jQuery UI?
Ans: jQuery is the core library. jQueryUI is built on top of it. If you use jQueryUI, you must also include jQuery.

Note: If you have any questions to add to this list then please put it comments. We will be glad to add them in this list. We will be keep on updating this list with new questions and share the updates on our Facebook or Twitter channel. If you are not following us then request you to please follow and stay updated.
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Friday, June 21, 2013

Use protocol less URL for referencing jQuery

Learnt something new today and thought of sharing. Most of us, include the reference of jQuery library (if Google CDN is used) like this,
http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
As you can see it is using HTTP protocol. The advantage of Google CDN files are cached up to one year which means that your users may not need to download jQuery at all. But when you move from HTTP to HTTPS pages, then you need to make sure that you are using https protocol for referencing jQuery as pages served via SSL should contain no references to content served through unencrypted connections.

Related Post:
And take a note that content served via SSL are not cacheable. Browsers will simply ignore content served over SSL for caching. So you need to make sure that if you are moving from HTTP to HTTPS url, use correct protocol for referencing jQuery library as well.

The better approach would be to use "protocol-less" URL.
//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
It looks strange and initially I also felt the same but "protocol-less" URL is the best way to reference third party content that’s available via both HTTP and HTTPS. When a URL’s protocol is omitted, the browser uses the underlying document’s protocol instead.

Thus, using the protocol-less URL allows a single script reference to adapt itself to what’s most optimal: HTTP and it’s full caching support on HTTP pages, and HTTPS on secured pages so that your users aren't confronted with a mixed content warning.

Must Read:
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Wednesday, June 5, 2013

jQuery .end() and Chaining

Before you go further, I assume that you know What is chaining in context of jQuery? If not, then first read "What is Chaining in jQuery?". To summarize Chaining in jQuery means to connect multiple functions, events on selectors. Main advantage of using chaining is that it makes code look clean and gives better performance. You should make a habit of using chaining.

Related Post:

You will find that chaining is very easy to implement and indeed it is. But consider a scenario, where in a <div> element, find all <p> and <span> elements and assign background color to them. Below jQuery code will exactly do the needful.
$(document).ready(function () {
   $('div').find('p').css("background", "yellow");
   $('div').find('span').css("background", "pink");
});
Can this be done using chaining? The first line of code $('div').find('p'), will select all the <p> tag element in <div> and change background color. Since using find() we have filtered out all <p> elements so we need to use selector again to select <span>tag element and we can't use chaining. Fortunately, jQuery has .end() function which end the most recent filtering operation in the current chain and return to its previous state. Like,
$(document).ready(function () {
    $('div')
       .find('p').css("background", "yellow")
       .end()
       .find('span').css("background", "pink");
});
This chain searches for <p> tag element in <div> and turns their backgrounds yellow. Then .end() returns the object to its previous state which was before the call to find(), so the second find() looks for <span> inside <div>, not inside <p>, and turns the matching elements' backgrounds to pink. The .end() method is useful primarily when exploiting jQuery's chaining properties.
See Complete Code
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Monday, May 27, 2013

Free jQuery Courses and Training material

In this post, we bring you a list of Free jQuery Course and Training Material which are useful from beginner to an expert. Of course, this blog has some useful, handy material but the below list has some serious and exceptional training materials which are created specifically for training purpose.

  • Try jQuery. Try jQuery walks you through the most fundamental building blocks of jQuery, from actually getting the library into your page to selecting, manipulating, and creating DOM elements, and reacting to user input.
  • Learn jQuery is the official learning portal for the library. If you're looking for explanations of the basics, workarounds for common problems, best practices, and how-tos, then that's the right place!
  • jQuery Fundamentals is designed to get you comfortable working through common problems you'll be called upon to solve using jQuery.
  • Lessons by appendTo() has collection of free video lessons on JavaScript, jQuery, events, methods and selectors.
  • Learn jQuery in 30 Days is a free newsletter course by tutsplus. Once you subscribe, each day you'll be sent a free video lesson in your email for 30 days.
  • jQuery Succinctly was written to express, in short-order, the concepts essential to intermediate and advanced jQuery development. Its purpose is to instill in you, the reader, practices that jQuery developers take as common knowledge.
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Thursday, April 18, 2013

Direct vs Delegated Events with jQuery on() method

jQuery added a new method called  on()  in release 1.7 which provides all functionality for attaching event handlers. And it has made other event handler event like live() and delegate() dead. This method was introduced due to performance issue with live() method.

Related Post:

There are 2 signaturs of  on()  method.
  1. .on(events[,selector] [,data ],handler(eventObject))
  2. .on(events[,selector] [,data])
In this post, we will focus on the one of the optional parameter named "selector". The official jQuery documentation about this parameter says,

" A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element."

As this is an optional parameter, so it can be omitted. The present/absence of this parameter defines Direct Event or Delegated Event. If it is absent, then it is called "Direct event", otherwise "Delegated event". First, we will see what Direct event means.

For example, there are 2 div element present on the page,
<div>First Div</div>
<div>Second Div</div>
And attach a click event on div element using on() method, which just alerts the clicked element text.
$(document).ready(function () {
    $('div').on('click', function() {
        alert("Clicked: " + $(this).html());
    });
});
So the above jQuery code instructs "HEY!!!! I want every div to listen to click event. And when you are clicked , give me alert." Now, this is absolutely fine and works like charm. This is called "Direct Event". But there is an issue with Direct events. Official jQuery document about Direct events says,

" Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()."

So for Direct events to work, the element has to present on the page. If it is added dynamically, it's not going to work.

Consider the same example, which now on click event adds a div element dynamically, after showing alert. But the click event don't get attached to dynamically added elements.
$(document).ready(function () {
    $('div').on('click', function() {
        alert("Clicked: " + $(this).html());
        $('<div>Dynamic Div</div>').appendTo('body');
    });
});
So when dynamically added div elements are clicked, nothing happens! As the event is not attached to them.
So, what is the solution now? Well, solution is to use "Delegated events". Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

When a selector is provided, the event handler is referred to as delegated. So let's modify the above jQuery code to have "Delegated event" instead of "Direct event".
$(document).ready(function () {
    $(document).on("click","div", function(){
        alert("Clicked: " + $(this).html());
        $('<div>Dynamic Div</div>').appendTo('body');
    });
});
So the jQuery code instructs "HEY!! document when your child element which is div gets clicked, give me alert and append a dynamic div to body." Using delegated event, you will find the same behavior for already present and dynamically added elements.
There is another advantage of using delegated event which is "much lower overhead". For example, On a table with 1,000 rows in its tbody, below code attaches a handler to 1,000 elements.
$("#Table tbody tr").on("click", function(event){
  alert($(this).text());
});
On the other side, using "Delegated event", attaching event handler to only one element which is tbody. The event only needs to bubble up one level (from the clicked tr to tbody).
$("#Table tbody").on("click", "tr", function(event){
  alert($(this).text());
});
Let's take another example, to explain "Delegated events". Consider following Html code.
<div id="container"> 
    <span> Span within Container div. </span>
    <br/> <span> Another span within Container div. </span>
</div>
And below is jQuery code to attach (delegated) click event on span element within div with ID "container" is,
$(document).ready(function () {
  var iCount = 1;
  $('div#container').on("click", "span", function () {
    alert("Clicked: " + $(this).html());
    var $dynSpan = $('<br/><span> Dynamic Span ' + iCount + '.</span>');
    $dynSpan.appendTo('div#container');
    iCount++;
  });
});
Here is another important tips "Attaching many delegated event handlers near the top of the document tree can degrade performance". For best performance, attach delegated events at a document location as close as possible to the target elements as done in above jQuery code. So instead of $(document).on("click","div#container span", function(){ , use $('div#container').on("click", "span", function () {

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Saturday, March 2, 2013

Now try.jQuery.com to learn jQuery interactively

How about learning jQuery like playing a game? Passing a hurdle, earning some badges to boost your score and confidence. Isn't is exciting? Well, indeed it is. Reading documentation, blogs, and forums are useful ways to learn how to use jQuery, but there is ultimately no substitute for actually writing code as while writing code one comes with issues, bugs and do mistakes and that is the best way to learn things.

So jQuery team has collaborated with Code School to create Try jQuery, a brand new introductory course with video and interactive examples to make it easier to take those first steps.


Related Post:

Try jQuery walks you through the most fundamental building blocks of jQuery, from actually getting the library into your page to selecting, manipulating, and creating DOM elements, and reacting to user input. The entire experience takes place in the browser, so there’s live feedback on your code as you complete the exercises and learn the basics.

The course takes about three hours to complete, but you can take it all at your own pace. Best of all, Try jQuery is completely free! If you’d like to save your progress and earn badges, you can sign up with Code School.

Try jQuery is a combination of videos, interactive console challenges, and writing code in the browser. You'll need about 2 hours of time to make it through everything.

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Friday, February 1, 2013

Common jQuery Mistakes

Well, Everyone makes mistakes and and best part would be not to repeat them again. You should "Always make new mistakes" :). jQuery is awesome library. But believe me, it can make you crazy if it is not used properly and efficiently. It can hit performance of your page and you don't even realize it. Ask yourself that as a developer while writing jQuery code do you really think about performance or it is only when your client shouts.

I have listed down 10 common jQuery mistakes from my personal experience and their fixes that you might be also doing while writing jQuery code.

Related Post:


1. Be courageous to remove jQuery


Sometimes things can be done easily via CSS without even thinking about jQuery but we don't realize it. Plain CSS is far better than jQuery. So be open and courageous to remove jQuery whenever needed.

2. Not using latest version of jQuery


jQuery team is keep on updating the jQuery library and the newer version comes with lots of bug fixes and performance enhancement. I understand that it is not always possible for you to use the latest version for your old projects but I suggest for your new projects, you can use latest version of jQuery.

Read "How to always reference latest version of jQuery"

3. Not using minified version of jQuery library


The jQuery library (when you download) comes in two versions.

1. Production (Compressed Version)
2. Development (Uncompressed Version)

For development purpose, you can choose the development version of .js file as if you want to make some changes then that can be easily done. But ensure that when your software or product goes on production, always use the production version of .js file as its size is 5 times lesser than the development version. This can save some amount of bandwidth.

4. Not loading jQuery from Google CDN


Google is sea of free services. Do you know that Google is also hosting jQuery libraries on its CDN(Content delivery network) and allows any website to use it for free.

Why to use Google CDN?
  • Caching: The most important benefit is caching. If any previously visited site by user is using jQuery from Google CDN then the cached version will be used. It will not be downloaded again.
  • Reduce Load: It reduces the load on your web server as it downloads from Google server's.
  • Serves fast : You will be also benefitted from speed point of view. As Google has dozen's of different servers around the web and it will download the jQuery from whichever server is closer to the user. Google's CDN has a very low latency, it can serve a resource faster than your webserver can.
  • Parellel Downloading: As the js file is on a separate domain, modern browsers will download the script in parallel with scripts on your domain.

Read "Why to use Google hosted jQuery CDN"

5. Not loading jQuery locally when CDN fails


It is a good approach to always use CDN but sometimes what if the CDN is down (rare possibility though) but you never know in this world as anything can happen. So if you have loaded your jQuery from any CDN and it went down then your jQuery code will stop working and your client will start shouting.

I always recommend that write the code, if jQuery library is not loaded properly then it should use your local copy of jQuery.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined')
{
  document.write(unescape("%3Cscript src='Scripts/jquery.1.9.0.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>
It first loads the jQuery from Google CDN and then check the jQuery object. If jQuery is not loaded successfully then it will references the jQuery.js file from hard drive location. In this example, the jQuery.js is loaded from Scripts folder.

6. Not using selectors efficiently


Be smart while using selectors. As there are many ways to select element using selectors but that doesn't mean that all are equal. Always try to use ID and Element as selector as they are very fast. Even the class selectors are slower than ID selector.

When IDs are used as selector then jQuery internally makes a call to getElementById() method of Java script which directly maps to the element.

When Classes are used as selector then jQuery has to do DOM traversal.So when DOM traversal is performed via jQuery takes more time to select elements. In terms of speed and performance, it is best practice to use IDs as selector.

7. Using jQuery selectors repeatedly


Take a look at below jQuery code. The selectors are used thrice for 3 different operation.
$("#myID").css("color", "red");
$("#myID").css("font", "Arial");
$("#myID").text("Error occurred!");
The problem with above code is, jQuery has to traverse 3 times as there are 3 different statements.But this can be combined into a single statement.
$("#myID").css({ "color": "red", "font": "Arial"}).text("Error occurred!");  
This will ensure that jQuery traverse only once through DOM while selecting the element.

8. Not knowing how selectors are executed


Do you know how the selectors are executed? Your last selectors is always executed first. For example, in below jQuery code, jQuery will first find all the elements with class ".myCssClass" and after that it will reject all the other elements which are not in "p#elmID".
$("p#elmID .myCssClass"); 

9. By not caching the stuff


Caching is an area which can give you awesome performance, if used properly and at the right place. While using jQuery, you should also think about caching. For example, if you are using any element in jQuery more than one time, then you must cache it. See below code.
$("#myID").css("color", "red");
//Doing some other stuff......
$("#myID").text("Error occurred!");
Now in above jQuery code, the element with #myID is used twice but without caching. So both the times jQuery had to traverse through DOM and get the element. But if you have saved this in a variable then you just need to reference the variable. So the better way would be,
var $myElement = $("#myID").css("color", "red");
//Doing some other stuff......
$myElement.text("Error occurred!");
So now in this case, jQuery won't need to traverse through the whole DOM tree when it is used second time. So in jQuery, Caching is like saving the jQuery selector in a variable. And using the variable reference when required instead of searching through DOM again.

10. Not checking while using various plugins


One of the great feature of jQuery is various plugins available created using jQuery are available for free. You like a jQuery plugin and start using it in your project. But while using plugins do you really consider,

  • File size
  • Performance of plugin
  • Browser Compatibility

Before using any plugin, always ensure that it must not hit performance of your page and it should not conflict with other plugins that you are using already.

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Wednesday, January 30, 2013

Learn how to use jQuery?

In this post, you will go through What is jQuery, why to use jQuery and learn how to use jQuery. jQuery is without any doubt is the most popular client side library. The popularity of jQuery is so much that it has become must for every developer. Before, you go further let me clear the very first doubt that "jQuery is not a language".


What is jQuery?


jQuery is a library written on top of the JavaScript. So it is a JavaScript library. It is a library for the JavaScript programmers, which makes web development like a piece of cake. jQuery helps the programmers to keep code simple and concise. The biggest advantage of jQuery is that jQuery library is designed to keep the things very simple and reusable. Motto is jQuery library is "Writing JavaScript code should be fun."

jQuery library simplifies the process of traversing and finding elements in HTML document. It provides methods to make animations, add ajax interaction to the page, provides an easy way to apply CSS to any items and provides an easy mechanism for binding and unbinding events. Lengthy JavaScript code can easily replaced by few lines of code in jQuery.


Why to use jQuery?


A question came that when all the things can be achieved using JavaScript then why to go for jQuery? Well the answer is that The jQuery library is has many easy to use functions and methods to make rich applications. And believe me these functions are fairly easy to learn and even it is not difficult for designers or freshers to learn. Due to it's simplicity, jQuery is pretty easy to learn and easy to write. jQuery is a client side language so it can be easily used with ASP.NET,PHP,JSP and Servlets.

Features of jQuery

  • It works on all browsers
  • It is fast and extensible
  • Make look UI stunning
  • Allows to access elements in the document
  • Easily apply CSS
  • Perform animation in better way
  • Ajax Interaction made easy
  • Change document’s content easily
  • Event handling made easy
  • Big pool of reusable plugins for various functionalities

Where to download jQuery?


jQuery file can be downloaded from jQuery Official website http://www.jquery.com/

jQuery Versions


jQuery library comes in 2 forms:
  • The uncompressed .js file is easy to read and modify, but it's around 190kb in size (at the time of writing).
  • The minified .js file has all comments, whitespace, and other unnecessary characters removed from the file, squeezing the whole library into a mere 23kb. Although you can't easily read the code, this is the version you'll want to place on your site, as it's much quicker for visitors to download.

How to use jQuery


To start with jQuery, first download the jQuery from it's official website (http://JQuery.com). Make sure you download the latest copy of the jQuery. You will find that it's a single JavaScript file. Yes, single JavaScript file with lots of magic. No installation is required, you just need to add reference of the jquery.js.
<script src="Script/jquery.js" type="text/javascript"></script>
I have copied the jquery.js and placed it in script directory. For demo, we will see how easily we can change the CSS.

Let's first take a look at HTML.
<h2>History of jQuery</h2>
<div id="content">
Initially it's was released in January 2006 but the very first stable version of jQuery 1.0 was released in August 2006. This version had support for CSS, events and Ajax. After that many version of jQuery were released and latest version is jQuery 1.9. 
</div>
In the above HTML, there is div element with ID "content". Now, we will see how to find the div and apply CSS to it using jQuery. Let's see CSS class.
<style type="text/css">
.ApplyColor
{
   font-family: calibri;
   font-size: 12pt;
   color: blue;
}
</style>
The first thing to learn about jQuery is $(document).ready() function. It is an entry point and gets called as soon as DOM is loaded. You need to place all your jQuery code within this function. JavaScript developers can think of window.onload() being similar to $(document).ready(). But it is different. Will explain later in the post.
<script type="text/javascript" language="javascript">
 $(document).ready(function() {
    $('#content').addClass('ApplyColor');
 });
</script>
A .ready() handler can be placed anywhere on the page and you can even have multiple ready handlers in the page. Now, if you view this page in browser, the you will see the div with content id is having gray background and white color foreground.


See Complete Code

window.onload() vs $(document).ready()


window.onload() and $(document).ready() are different. document.ready() gets called as soon as your DOM is loaded. It does not wait for the contents to get loaded fully. For example, there are very heavy images on any web page and takes time to load. If you have used window.onload() then it will wait until all your images are loaded fully, hence it slows down the execution. On the other side, document.ready() does not wait for elements to get loaded.

What are jQuery CDN?


CDN Stands for Content Distribution Network or also called Content Delivery Network is a large distributed system of servers deployed in multiple data centers in the Internet. The goal of a CDN is to serve content to end-users with high availability and high performance. There are several advantage of using CDN.
  • Reduce Load: It reduces the load on your web server as it downloads from Google server's.
  • Caching: The most important benefit is caching. If any previously visited site by user is using jQuery from any CDN then the cached version will be used. It will not be downloaded again.
  • Serves fast: You will be also benefited from speed point of view. As CDN has dozen's of different servers around the web and it will download the jQuery from whichever server is closer to the user.
  • Parallel Downloading: As the jQuery js file is on a separate domain, modern browsers will download the script in parallel with scripts on your domain.
There are 3 different CDN that provide jQuery.
  • Google
  • Microsoft
  • jQuery
Code to load jQuery Framework from Google CDN
<script  type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js">
</script>
Code to load jQuery Framework from Microsoft CDN
<script  type="text/javascript"
    src="http://ajax.microsoft.com/ajax/jquery/jquery-1.9.0.min.js">
</script>
Code to load jQuery Framework from jQuery Site(EdgeCast CDN)
<script  type="text/javascript"
    src="http://code.jquery.com/jquery-1.9.0.min.js">
</script>
It is a good practice to use CDN but what if the CDN is down (rare possibility though) but you never know in this world as anything can happen. So if you have loaded your jQuery from any CDN and it went down then your jQuery code will stop working and your client will start shouting. Read "How to load jQuery locally when CDN fails".

Note:When this post is written, the latest version of jQuery is 1.9

Summary


This post gives you clear idea about what is jQuery and how to start with it. It is not possible to cover everything but this post is good enough to kick start. So start learning jQuery and start using it. Some of my previous series of articles will help you to learn jQuery.
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...