Monday 30 March 2015

Top 70 Jquery Interview question and answer


Top 70 Interview question and answer

1. What is jQuery?

jQuery is a lightweight JavaScript library that emphasizes interaction between 
JavaScript and HTML. 
                           It's very simple but most valuable Question on jQuery means jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, animating, event handling, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript. Jquery is build library for javascript no need to write your own functions or script jquery all ready done for you  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.


2. Why jQuery is needed?

jQuery is needed for the following list:
  • Used to develop browser compatible web applications
  • Improve the performance of an application
  • Very fast and extensible
  • UI related functions are written in minimal lines of codes

3. What are the fastest selectors in jQuery?

 ID and element selectors are the fastest selectors in jQuery.


4. What are the slow selectors in jQuery?

 class selectors are the slow compare to ID and element.


5. Why do we use jQuery?

 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.

6. How JavaScript and jQuery are different?

 JavaScript is a language While jQuery is a library built in the JavaScript language that helps to use the JavaScript language.

7. Is jQuery a library for client scripting or server scripting?

. Client side scripting.


8. What is the basic need to start with jQuery?

 To start with jQuery, one need to make reference of it's library. The latest version of jQuery can be downloaded from jQuery.com.


9. Which is the starting point of code execution in jQuery?

 The starting point of jQuery code execution is $(document).ready() function which is executed when DOM is loaded.


10. Is jQuery replacement of Java Script?

 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.


11. What does dollar sign ($) means in jQuery?

 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(){
});

12. Can we have multiple document.ready() function on the same page?

YES. We can have any number of document.ready() function on the same page.


13. Can we use our own specific character in the place of $ sign in jQuery?

 Yes. It is possible using jQuery.noConflict().


14. Is it possible to use other client side libraries like MooTools, Prototype along with jQuery?

 Yes.

15. Is there any difference between body onload() and document.ready() function?

 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 bodyonload 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.

16. What is a CDN?

 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.


17. Which are the popular jQuery CDN? and what is the advantage of using CDN?

 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


18. How to load jQuery from CDN?

 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>

19. How to load 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.

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.


20. What are selectors in jQuery and how many types of selectors are there?

 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.

21. How do you select element by ID in jQuery?

 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')

22. What does $("div") will select?

 This will select all the div elements on page.


23. How to select element having a particular class (".selected")?

 $('.selected'). This selector is known as class selector. We need to prefix the class name with "." (dot).


24. What does $("div.parent") will select?

 All the div element with parent class.

25. How jQuery 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");

26. Which is fast document.getElementByID('txtName') or $('#txtName').?

 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.


27. Difference between $(this) and 'this' in jQuery?

 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);
  });
});

28. How do you check if an element is empty?

 There are 2 ways to check if element is empty or not. We can check using ":empty" selector.


    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
  }
});  

29. How do you check if an element exists or not in jQuery? 

 Using jQuery length property, we can ensure whether element exists or not.
$(document).ready(function(){
    if ($('#element').length > 0){
       //Element exists
  }
});

30. What is the use of jquery .each() function?

 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.


31. What is the difference between jquery.size() and jquery.length?

 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.


32. What is the difference between $('div') and $('<div/>') in jQuery?

 $('<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.



33. What is the difference between parent() and parents() methods in jQuery?

The basic difference is the parent() function travels only one level in the DOM tree, where parents() function search through the whole DOM tree.


34. What is the difference between eq() and get() methods in jQuery?

 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. 



35. What is the difference between .js and .min.js?

 jQuery library comes in 2 different versions Development and Production/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.


36. Why there are two different version of jQuery library?

 jQuery library comes in 2 different versions.
  1. Development 
  2. Production/Deployment
The development 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 development 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.


37. How to always reference latest version of jQuery?

When you reference the jQuery on your web page, you have to specify the version number also.

<script type=”text/javascript”
src=”http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js”>
</script>
Above code will always load the 1.5.1 version of jQuery. If you reference the latest jQuery then you don’t need to change the code every time the new version of jQuery is released.
To achieve this you have to use following code
<script type=”text/javascript”
src=”http://code.jquery.com/jquery-latest.min.js”>
</script>


This code will always reference the latest version of jQuery in your page.

38. What is resize() function in jQuery?

The resize() function is called whenever the browser size is changed. This event can be only used with $(window).
Syntax:
.resize([event_data], handler(event_object))
-The “event_data” is the data to be sent to the handler.
-The “handler(event_object)” is a function to be called each time when the window is resized.
For example

$(window).resize(function() {
$('#message).text('window is resized to ' + $(window).width() + ‘x’ + $(window).height());
});

39. 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"});
});


40. What is .siblings() method in jQuery?

  • When we want to fetch siblings of every elements in the set of matched elements then we can use siblings() method.
  • We filter the elements fetched by an optional selector.
  • Syntax : .siblings( [selector])
  • “selector” is the selector expression which specify the matched elements.
For example
<ul> <li> item 1 </li> <li id=”second_item”> item 2 </li> <li class=”myitem”> item 3 </li> <li class=”myitem”> item 4 </li> </ul>
Now we want to find the siblings of the element of id “second_item” and change the text color to Blue :
$(‘li.second_item’).siblings().css(‘color’,’blue’);
If we want specific sibling elements for example the elements having class “myitem” then we can pass a optional selector: $(‘li.second_item’).siblings(‘.myitem’).css(‘color’,’blue’);

41. Explain width() vs css(‘width’).

  • In jQuery, there are two way to change the width of an element.
  • One way is using .css(‘width’) and other way is using .width().
For example
$(‘#mydiv’).css(‘width’,’300px’); $(‘#mydiv’).width(100);
  • The difference in .css(‘width’) and .width() is the data type of value we specify or return from the both functions.
  • In .css(‘width’) we have to add “px” in the width value while in .width() we don’t have to add.
  • When you want to get the width of “mydiv” element then .css(‘width’) will return ‘300px’ while .width() will return only integer value 300.

42. What is jQuery.noConflict?

 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();
});  

43. What is the use of jQuery.data()?

  • jQuery.data() is used to set/return arbitrary data to/from an element.
  • Syntax: jQuery.data(element, key, value)
  • “element” is the DOM element to which the data is associated.
  • “key” is an arbitrary name of the piece of data.
  • “value” is value of the specified key.
  • Suppose we want to set the data for a span element:
jQuery.data(span, “item”, { val1: 10, val2: "myitem" });
If we want to retrieve the data related to div element and set it to label’s data:
$("label:val1").text(jQuery.data(div, "item").val1); $("label:val2").text(jQuery.data(div, "item").val2);

44. How to disable jQuery animation?

 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.


45. How do you stop the currently-running animation?

 Using jQuery ".stop()" method.


46. Explain .empty() vs .remove() vs .detach().

-.empty() method is used to remove all the child elements from matched elements.
-.remove() method is used to remove all the matched element. This method will remove all the jQuery data associated with the matched element.
-.detach() method is same as .remove() method except that the .detach() method doesn’t remove jQuery data associated with the matched elements.
-.remove() is faster than .empty() or .detach() method.


Syntax:

$(selector).empty();
$(selector).remove();
$(selector).detach();


47. What is the difference between .empty(), .remove() and .detach() methods in jQuery?

 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.


48. How to create clone of any object using jQuery?

 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;
  });
});

49. Does events are also copied when you clone any element in jQuery?

 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');
  });

50. What is difference between prop and attr?

 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.



51. What is event.PreventDefault?

 The event.preventDefault() method stops the default action of an element from happening. For example, Prevents a link from following the URL.


52. What is the difference between event.PreventDefault and event.stopPropagation?

 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.


53. What is the difference between event.PreventDefault and "return false"?

 e.preventDefault() will prevent the default event from occurring, e.stopPropagation() will prevent the event from bubbling up and return false will do both.


54. What is the difference between event.stopPropagation and event.stopImmediatePropagation?

 event.stopPropagation() allows other handlers on the same element to be executed, whileevent.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.


55. What is jQuery Selectors? Give some examples.

  • jQuery Selectors are used to select one or a group of HTML elements from your web page.
  • jQuery support all the CSS selectors as well as many additional custom selectors.
  • jQuery selectors always start with dollar sign and parentheses: $()
  • There are three building blocks to select the elements in a web document.
1) Select elements by tag name
Example: $(div)

It will select all the div elements in the document.


2) Select elements by ID
Example: $(#xyzid”)

It will select single element that has an ID of xyzid


3) Select elements by class
Example:

 $(“.xyzclass”)

It will select all the elements having class xyzclass

56. How can we give face effect in jQuery?

  • In jQuery we have three methods to give the fade effect to elements: fadeIn, fadeOut and fadeTo
  • This methods change the opacity of element with animation.
Syntax:
$(selector).fadeIn(speed,callback)
$(selector).fadeOut(speed,callback)
$(selector).fadeTo(speed,opacity,callback)
  • “speed” can be one of following values : “slow”, “fast”, “normal” or milliseconds
  • “opacity” specify the value that allows the fading to given opacity.
  • “callback” is the function which we want to run once the fading effect is complete.
For example

$("clickme").click(function(){
$("mydiv").fadeTo("slow",0.50);
});

$("clickme").click(function(){
$("mydiv").fadeOut(3000);
});.

57. Explain the animate function.

-The animate function is used to apply the custom animation effect to elements.
-Syntax:

$(selector).animate({params}, [duration], [easing], [callback])
  • “param” defines the CSS properties on which you want to apply the animation.
  • “duration” specify how long the animation will run. It can be one of following values : “slow”, “fast”, “normal” or milliseconds
  • “easing” is the string which specify the function for the transition.
  • “callback” is the function which we want to run once the animation effect is complete.
For example

<div id="clickToAnimate">
Click Me
</div>
<div id="mydiv" style=”width:200px; height:300px; position: relative; right: 20px;">
</div>


Following is the jQuery to animate opacity, left offset, and height of the mydiv element

$('# clickToAnimate’).click(function() {
$('#book').animate({
opacity: 0.30,
left: '+=20',
height: 'toggle'
}, 3000, function() {
// run after the animation complete.
});
})
;

58. Explain bind() vs live() vs delegate() methods.

-The bind() method will not attach events to those elements which are added after DOM is loaded while live() and delegate() methods attach events to the future elements also.
-The difference between live() and delegate() methods is live() function will not work in chaining. It will work only on an selector or an element while delegate() method can work in chaining.
For example

$(document).ready(function(){
$("#myTable").find("tr").live("click",function(){
alert($(this).text());
});
});


Above code will not work using live() method. But using delegate() method we can accomplish this.


$(document).ready(function(){
$("#dvContainer")children("table").delegate("tr","click",function(){
alert($(this).text());
});
});

59. Explain the each() function.

-The each() function specify the function to be called for every matched element.
Syntax:

$(selector).each(function (index, element))
  • “index” is the index position of the selector.
  • “selector” specifies the current selector where we can use “this” selector also.
  • In the case when we need to stop the each loop early then we can use “return false;”
For example

$("#clickme").click(function(){
$("li").each(function(){
document.write($(this).text())
});
});


This will write the text for each “li” element.

60. Explain slideToggle() effect.

-slideToggle() effect is used to give animated sliding effect to an element.

Syntax:


slideToggle([ duration] [, easing] [, callback])
  • “duration” is the number specifying how long the animation will run.
  • “easing” is the string which specify the function for the transition.
  • “callback” is the function which we want to run once the animation is complete.
  • If the element is visible then this effect will slide the element up side and make it completely hidden. If the element is hidden then slideToggle() effect will slide it down side and make it visible.
  • We can specify the toggle speed with this effect.
For example

$("#clickme").click(function(){
$("#mydiv").slideToggle(“slow”, function(){
//run after the animation is complete.
});
});

61. What is difference between $(this) and ‘this’ in jQuery?

Refer the following example

$(document).ready(function(){
$(‘#clickme’).click(function(){
alert($(this).text());
alert(this.innerText);
});
});


-this and $(this) references the same element but the difference is that “this” is used in traditional way but when “this” is used with $() then it becomes a jQuery object on which we can use the functions of jQuery.
-In the example given, when only “this” keyword is used then we can use the jQuery text() function to get the text of the element, because it is not jQuery object. Once the “this” keyword is wrapped in $() then we can use the jQuery function text() to get the text of the element.

62. What is the use of param() method.

  • The param() method is used to represent an array or an object in serialize manner.
  • While making an ajax request we can use these serialize values in the query strings of URL.
  • Syntax: $.param(object | array, boolValue)
  • “object | array” specifies an array or an object to be serialized.
  • “boolValue” specifies whether to use the traditional style of param serialization or not.
For example:

personObj=new Object();
empObject.name="Arpit";
empObject.age="24";
empObject.dept=”IT”;
$("#clickme").click(function(){
$("span").text($.param(empObject));
});


It will set the text of span to “name=Arpit&age=24&dep=IT”

63. What is jQuery.holdReady() function?

-By using jQuery.holdReady() function we can hold or release the execution of jQuery’s ready event.
-This method should be call before we run ready event.
-To delay the ready event, we have to ca
ll

jQuery.holdReady(true);
-When we want to release the ready event then we have to call

jQuery.holdReady(false);


-This function is helpful when we want to load any jQuery plugins before the execution of ready event.
For example

$.holdReady(true);
$.getScript("xyzplugin.js", function() {
$.holdReady(false);
});


64. Explain .bind() vs .live() vs .delegate() vs .on()

 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 selectorbind() 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.


65. 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!!!');

66. How to read, write and delete cookies in jQuery?

-To deal with cookies in jQuery we have to use the Dough cookie plugin.
-Dough is easy to use and having powerful features.
-Create cookie


$.dough("cookie_name", "cookie_value");
Read Cookie
$.dough("cookie_name");
Delete cookie
$.dough("cookie_name", "remove");

67. Is window.onload is different from document.ready()?

- The window.onload() is Java script function and document.ready() is jQuery event which are called when page is loaded.
- The difference is that document.ready() is called after the DOM is loaded without waiting for all the contents to get loaded. While window.onload() function waits until the contents of page is loaded.
- Suppose there is very large image on a page, at that time window.onload() will wait until that image is loaded totally.
- So while using the window.onlaod() function the execution will be slow, but the document.ready() will not wait until the image is loaded.

68. What is Chaining in jQuery?

- Chaining is very powerful feature of jQuery.
- Chaining means specifying multiple function and/or selectors to an element.
- Examine the below example


$(document).ready(function(){
$('#mydiv').css('color', 'blue');
$('#mydiv').addClass('myclass');
$('#mydiv').fadeIn('fast');
}
By using chaining we can write above code as follows
$(document).ready(function(){
$('#mydiv').css('color', 'blue').addClass('myclass').fadeIn('fast');
});


-Advantage of chaining is that it makes your code simple and simple to manage.
-The execution becomes faster because the code search for the element only once.

69. What is difference between sorting string array and sorting numerical array in jQuery?

The sort method is used to sort any array elements. It sorts the string elements alphabetically.
For example

$(document).ready(function(){
var mylist = [ “Apple”,”Orange”,”Banana”];
mylist = mylist.sort();
$(“#mydiv”).html(list.join(“”));
});


It will give following output

Apple
Banana
Orange


Now we declare a numerical array and use sort() method to sort its elements.

$(document).ready(function(){
var mylist = [ “20”,”3””100”,”50”];
mylist = mylist.sort();
$(“#mydiv”).html(list.join(“”));
});


It will give following output

100
20
3
50

70 What is difference between prop and attr?

  • In jQuery both prop() and attr() function is used to set/get the value of specified property of an element.
  • The difference in both the function is that attr() returns the default value of the property while the prop() returns the current value of the property.
For example
<input value="My Value" type="text"/>

$('input').prop('value', 'Changed Value');


-.attr('value') will return 'My Value'
-.prop('value') will return 'Changed Value'

2 comments: