Saturday, 9 January 2021

jQuery Interview Questions and Answers

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

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

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


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


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

Ans. Client side scripting.
 

6. Is jQuery a W3C standard?

Ans: No. jQuery is not a W3C standard.
 

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

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

9. 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(){

});

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

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

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

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

Ans: Yes.
 

13. 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();

});  

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

 

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

Ans: 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.
 

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

Ans: 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 a 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.
 

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

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

Ans: There are 3 popular jQuery CDNs.

1. Google.

2. Microsoft

3. jQuery.


Advantages 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

 

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

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

It first loads the jQuery from Google CDN and then checks the jQuery object. If jQuery is not loaded successfully then it will reference the jQuery.js file from the hard drive location. In this example, the jQuery.js is loaded from the Scripts folder.
 

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

 

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

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

Ans: This will select all the div elements on page.
 

24. 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).
 

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

Ans: All the div element with parent class.
 

26. What are the fastest selectors in jQuery?

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

27. What are the slow selectors in jQuery?

Ans: class selectors are the slow compare to ID and element.
 

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

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

30. 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);

  });

});

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

Ans: There are 2 ways to check if an 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

  }

});  

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

Ans: Using jQuery length property, we can ensure whether an element exists or not.

 

$(document).ready(function(){

    if ($('#element').length > 0){

       //Element exists

  }

});

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

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

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

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

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

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

});

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

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

Ans: Using jQuery ".stop()" method.
 

41. 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 elements of the matched element where remove() method removes a 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
 

42. 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 match 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.
 

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

 

44. 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;

  });

});

45. Do 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');

  });

46. What is the 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 ,a 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.
 

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

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

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

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

Ans: 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.
 

51. How to check if number is numeric while using jQuery 1.7+?

Ans: Using "isNumeric()" function which was introduced with jQuery 1.7.
 

52. How to check data type of any variable in jQuery?

Ans: Using $.type(Object) which returns the built-in JavaScript type for the object.
 

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

    });

});​

54. Can you include multiple versions of jQuery? If yes, then how are they executed?

Ans: Yes. Multiple versions of jQuery can be included in the same page.
 

55. In what situation would you use multiple versions 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 versions but for your own jQuery code, you would like to use newer versions. So because of this dependency, multiple versions of jQuery may be required sometimes on a single page.

Below code shows how to include multiple versions of jQuery.

 

<script type='text/javascript' src='js/jquery_1.9.1.min.js'></script>

 

<script type='text/javascript'>

 var $jq = jQuery.noConflict();

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

56. 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);

});

57. 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. Find out more here.
 

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

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

Find out more here.

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

61. Can we use jQuery to make ajax requests?

Ans: Yes. jQuery can be used for making ajax requests.
 

62. What are various methods to make ajax requests 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.
     

63. 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 a number of reasons 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.
 

64. What are deferred and promise objects 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.
 

65. Can we execute/run multiple Ajax requests simultaneously in jQuery? If yes, then how?

Ans: Yes, it is possible to execute multiple Ajax requests simultaneously or in parallel. Instead of waiting for the 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 requests 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.
 

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

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

68. Does jQuery 2.0 supports IE?

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

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

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

71. 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" 

}

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

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

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

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

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

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

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

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

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

81. What is JQuery.noConflict?

Ans:  jQuery no-conflict is an option given by jQuery to overcome the conflicts between the different js frameworks or libraries. When we use jQuery no-conflict mode, we are replacing the $ to a new variable and assigning to jQuery some other JavaScript libraries. Also use the $ (Which is the default reference of jQuery) as a function or variable name what jQuery has. And in our development life, we are not at all strict to only jQuery.

82. What is a CDN?

Ans: Content Delivery Network (CDN) in simple terms is a collection of servers spread across the globe. In other words, a CDN is a network of servers in which each request will go to the closest server.

Need For a CDN

For any web application, data can be categorized into either static or dynamic content. Dynamic content is the one that generally comes from a database. Static content is like CSS, images, JavaScript, flash files, video files and so on.

Now one may ask, how are requests served when a user enters an URL into the browser? Interesting, let's have a look at it. Before knowing a CDN and its usage, it is very important to understand this process:

 83. What is the difference between $(window).load and $(document).ready function in jQuery?

Ans:  $(window).load is an event that fires when the DOM and all the content (everything) on the page is fully loaded. This event is fired after the ready event.

Let's look at an example.

  1. <script type="text/javascript" lang="ja">  

  2.     $(window).load(function() {  

  3.         alert("Window load event fired");  

  4.     });  

  5.   

  6.     $(document).ready(function() {  

  7.         alert("document ready event fired");  

  8.     });  

  9. </script>  

In the preceding JavaScript, we created an anonymous function that contains an alert message. So, when the preceding two events are fired an alert window will pop-up.

Run the application and let's see which event is fired first.

The document ready function will be fired first.

fired

Then the window load event will be fired.

window load event

When to use $(window).load instead of $(document).ready

In most cases, the script can be executed as soon as the DOM is fully loaded, so ready() is usually the best place to write your JavaScript code. But there could be some scenario where you might need to write scripts in the load() function. For example, to get the actual width and height of an image.

As we know the $(window).load event is fired once the DOM and all the CSS, images and frames are fully loaded. So, it is the best place to write the jQuery code to get the actual image size or to get the details of anything that is loaded just before the load event is raised.


 84: What are the advantages of jQuery?

Ans: In JavaScript we write more code because it doesn't have more functions like animation effects functions and event handling. So if you use JavaScript, developers write more code and they often feel embraced when they execute the code on the browser and get a problem related to cross-browser support. To solve these types of problems, John has created a JavaScript library with a nice motto, "write less and do more" in 2006; that is called jQuery. So you can use all the functions and other capabilities available in JavaScript. It saves developer's time, testing efforts, lines of code and improves their productivity and efficiency of development. The following are some important points to use jQuery.

  • Fully documented

  • Lot of plugins

  • Small size

  • Everything works in IE 6.0+, FF 2.0+, Safari 3.0+, Chrome and Opera 9.0+

85. How to remove a DOM Element using jQuery?

Ans:  Sometimes we get a requirement to delete all child nodes and remove DOM elements using jQuery to make a dynamic web page. In this scenario jQuery provides a couple of methods to remove DOM elements. Here are the options:

  • empty()

  • remove()

  • html()

86. What is the use of jQuery.ajax method()?

Ans: The ajax() method is used to do an AJAX (asynchronous HTTP) request. It provides more control of the data sending and on response data. It allows the handling of errors that occur during a call and the data if the call to the ajax page is successful.

Here is the list of some basic parameters required for jQuery.ajax Method:

  • type: Specifies the type of request (GET or POST).

  • url: Specifies the URL to send the request to. The default is the current page.

  • contentType: The content type used when sending data to the server. The default is "application/x-www-form-urlencoded".

  • dataType: The data type expected of the server response.

  • data: Specifies data to be sent to the server.

  • success(result,status,xhr): A function to run when the request succeeds.

  • error(xhr,status,error): A function to run if the request fails.

87. What is an attribute in jQuery?
Ans: There are many important properties of DOM or HTML elements such as for the <img> tag the src, class, id, title and other properties. jQuery provides ways to easily manipulate an elements attribute and gives us access to the element so that we can also change its properties.

  1. attr( properties ) - Set a key/value object as properties to all matched elements.

  2. attr( key, fn ) - Set a single property to a computed value, on all matched elements.

  3. removeAttr( name ) - Remove an attribute from each of the matched elements.

  4. hasClass( class ) - Returns true if the specified class is present on at least one of the set of matched elements.

  5. removeClass( class ) - Removes all or the specified class(es) from the set of matched elements.

  6. toggleClass( class ) - Adds the specified class if it is not present, removes the specified class if it is present.

  7. html( ) - Gets the HTML contents (innerHTML) of the first matched element.

  8. html( val ) - Sets the HTML contents of every matched element.

  9. text( ) - Gets the combined text contents of all matched elements.

  10. text( val ) - Sets the text contents of all matched elements.

  11. val( ) - Gets the input value of the first matched element.

88. What is $.each() function in jQuery?

Ans: The "jQuery.each()" function is a general function that will loop through a collection (object type or array type). Array-like objects with a length property are iterated by their index position and value. Other objects are iterated on their key-value properties. The "jQuery.each()" function however works differently from the $(selector).each() function that works on the DOM element using the selector. But both iterate over a jQuery object.

For example: If we pass an array to the each() function, it iterates over items in the array and accesses both the current item and its index position.

89: What is the difference between bind() and live() method in jQuery ?
Ans: The binding of event handlers are the most confusing part of jQuery for many developers working on jQuery projects. Many of them unsure of which is better to use. In this article we will see the main differences between Bind and Live methods in jQuery.

Bind() Method

The bind method will only bind event handlers for currently existing items. That means this works for the current element.

Example

  1. $(document).ready(function () {   

  2.    $('P').bind('click', function () {  

  3.       alert("Example of Bind Method");  

  4.       e.preventDefault();  

  5.    });   

  6. });  

Live() Method

The Live method can bind event handlers for currently existing items or future items.

Example

  1. $(document).ready(function() {  

  2.     $('P').live('click', function() {  

  3.         alert("Example of live method");  

  4.         e.preventDefault();  

  5.     });  

  6.     $('body').append('<p>Adding Future items</p>');  

  7.   

  8. });  

 90: What is jQuery.holdReady() function?
Ans: jQuery.holdReady() function is what we can hold or release the execution of jQuery's ready event. This method should be called before we run the ready event. To delay the ready event, we need to call jQuery.holdReady(true);

When we want to release the ready event then we need to call jQuery.holdReady(false);

This function is helpful when we want to load any jQuery plugin before the execution of the ready event or want to perform certain events/functions before document.ready() loads. For example, some information.

91: What is resize() function in jQuery?
Ans: This method in jQuery is used for changing of the size of the element. You can use by .resize() function. For more visit the following link:

92. What is slice() method in jQuery ?
Ans: This method selects a subset of the matched elements by giving a range of indices. In other words, it gives the set of DOM elements on the basis of it's parameter (start, end).

Syntax: .slice( start, end[Optional] ) 

Start: This is the first and mandatory parameter of the slice method. This specifies from where to start to select the elements. 

End: This is an optional parameter. It specifies the range of the selection. This indicates where to stop the selection of elements, excluding end element. 

Note: The Negative Indices started from -1. This last element is denoted by index -1 and so on.

93. jQuery event.preventDefault() Method?

Ans: The event.preventDefault() method stops the default action of an element from happening.

For example:

Prevent a submit button from submitting a form

Prevent a link from following the URL.

$("a").click(function(event){

    event.preventDefault();

});


94. Difference between push and pop in jquery?

Ans: PUSH: The push() method adds new items to the end of an array, and returns the new length.

     POP:  The pop() method removes the last element of an array, and returns that element.


95. What is jQuery - Chaining?

Ans : Chaining allows us to run multiple jQuery methods (on the same element) within a single statement.


jQuery Method Chaining

Until now we have been writing jQuery statements one at a time (one after the other).

However, there is a technique called chaining, that allows us to run multiple jQuery commands, one after the other, on the same element(s).

Tip: This way, browsers do not have to find the same element(s) more than once.

To chain an action, you simply append the action to the previous action.

The following example chains together the css(), slideUp(), and slideDown() methods. The "p1" element first changes to red, then it slides up, and then it slides down:

Example

$("#p1").css("color", "red").slideUp(2000).slideDown(2000);


96. Definition and Usage of stopPropagation?

Ans: The event.stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed.

Tip: Use the event.isPropagationStopped() method to check whether this method was called for the event.



 




No comments:

Post a Comment

Constructor

1. What is a Constructor in C#? A constructor is a special method that runs when an object of a class is created. It initializes the object ...