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 3x. These interview questions will help you to prepare for the interviews.

If there is any new jQuery interview question that have been asked to you, kindly post it in the the comment section.


 

1. What is jQuery?

Ans:

jQuery is not a programming language but a well written JavaScript code. It is a JavaScript code, which do document traversing, event handling, Ajax interactions and Animations.

2. Why jQuery is needed?

Ans:

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. Whether jQuery HTML work for both HTML and XML documents?

Ans:

No, jQuery HTML only works for HTML documents not for XML Documents.

4. What are the methods used to provide effects?

Ans:

Some of the effects methods are:

  • Show()
  • Hide()
  • Toggle()
  • FadeIn() and
  • FadeOut()

5. What is the advantage of using minimized version of jQuery?

Ans:

Efficiency of web page increases when minimized version of jQuery is used.min.js file will be more than 50% less than the normal js file. Reduction in the file size makes the web page faster.

6. Is jQuery is a JavaScript or JSON library file?

Ans:

jQuery is a library of JavaScript file and it consists of DOM, event effects and the Ajax functions. jQuery is said to be a single JavaScript file.

7. Which operating system is more compatible with jQuery?

Ans:

Mac, Windows and Linux are more compatible with the jQuery.

8. How can we include jQuery library in ASP.Net project?

Ans:

Download the jQuery library from jQuery.com and include that reference in the asp.net page.

9. Which command will give a version of jQuery?

Ans:

The command $.ui.version returns jQuery UI version.

10. In what scenarios jQuery can be used?

Ans:

jQuery can be used in following scenarios:

  • Apply CSS static or dynamic
  • Calling functions on events
  • Manipulation purpose
  • Mainly for Animation effects


 

11. What is the difference between find and children methods?

Ans:

Find method is used to find all levels down the DOM tree but children find single level down the DOM tree.

12. What is jQuery connect?

Ans:

A ‘ jQuery connect’ is a plugin used to connect or bind a function with another function. Connect is used to execute function from any other function or plugin is executed.

13. How to use connect?

Ans:

Connect can be used by downloading jQuery connect file from jQuery.com and then include that file in the HTML file. Use $.connect function to connect a function to another function.

14. What are the features of jQuery, has been used in web applications?

Ans:

jQuery uses features like Sliding, File uploading and accordian in web applications.

15. What are the browser related issues for jQuery?

Ans:

Browser compatibility of jQuery plugin is an issue and needs lot of time to fix it.

16. Whether we need to add jQuery file in both Master and Content page?

Ans:

jQuery file should be added to the Master page and can use access from the content page directly without having any reference to it.

17. What are the basic selectors in jQuery?

Ans:

Following are the basic selectors in jQuery:

  • Element ID
  • CSS Name
  • Tag Name
  • DOM hierarchy

18. Can we call C# code behind using jQuery?

Ans:

Yes, we can call C# code from jQuery as it supports .net application.

19. What is the use jQuery.data method?

Ans:

jQuery.data methods is used to associate the data with the DOM nodes and the objects. This data method makes the jQuery code clear and concise.

20. What is the use of each function in jQuery?

Ans:

Each function is used to iterate each and every element of an object. It is used to loop DOM elements, arrays and the object properties.




 

21. What is the difference between size and length of jQuery?

Ans:

Size and length both returns the number of element in an object. But length is faster than the size because length is a property and size is a method.

22. Can we add more than one ‘document.ready’ function in a page?

Ans:

Yes, we can add more than one document.ready function in a page. But, body.onload can be added once in a page.

23. What is the use of jQuery load method?

Ans:

jQuery load method is a powerful AJAX method which is used to load the data from a server and assign the data into the element without loading the page.

24. Whether our own specific characters are used in place of $ in jQuery?

Ans:

Yes, We can use our own variable in place of $ by using the method called no Conflict () method.
var sample = $.noConflict()

25. What are the four parameters used for jQuery Ajax method?

Ans:

The four parameters are
URL – Need to specify the URL to send the request
type – Specifies type of request(Get or Post)
data – Specifies data to be sent to server
Cache – Whether the browser should cache the requested page

26. What is the use of jQuery filter?

Ans:

The jQuery filter is used to filter the certain values from the object list based on the criteria. Example is to filter certain products from the master list of products in a cart website.

27. Which program is useful for testing jQuery?

Ans:

QUnit is used to test jQuery and it is very easy and efficient.

28. What is CDN?

Ans:

CDN is abbreviated as Content Distribution network and it is said to be a group of companies in different location with network containing copies of data files to maximize bandwidth in accessing the data.

29. What are the two types of CDNs?

Ans:

There are two types of CDNs:
Microsoft – Load jQuery from Ajax CDN
Google – Load jQuery from Google libraries API

30. Which sign is used as a shortcut for jQuery?

Ans:

Dollar ($) sign is used as a shortcut for jQuery.


 

31. Is jQuery is a client or server scripting?

Ans:

jQuery is a client scripting.

32. What is the script build up by jQuery?

Ans:

jQuery is a Javascript file and it is single javascript file that contains common DOM, event effects and Ajax functions.

33. How can we debug jQuery?

Ans:

There are two ways to debug jQuery:
Debugger keyword

  • Add the debugger to the line from where we have to start debugging and then run Visual Studio in Debug mode with F5 function key.
  • Insert a break point after attaching the process

34. What are all the ways to include jQuery in a page?

Ans:

Following are the ways to include jQuery in a page:

  • Local copy inside script tag
  • Remote copy of jQuery.com
  • Remote copy of Ajax API
  • Local copy of script manager control
  • Embedded script using client script object

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

Ans:

jQuery.ajax method is used for asynchronous HTTP requests.

36. Where can we download JQuery?

Ans:

jQuery javascript can be downloaded from jQuery official website – www.jquery.com

37. Is jQuery is a replacement of JavaScript?

Ans:

No, jQuery is not a replacement of JavaScript.

38. What is called chaining?

Ans:

Chaining is used to connect multiple events and functions in a selector.

39. What are the advantages of jQuery?

Ans:

Following are the advantages of jQuery:

  • Just a JavaScript enhancement
  • Coding is simple, clear, reusable
  • Removal of writing more complex conditions and loops

40. Whether C# code behind can be called from jQuery?

Ans:

Yes, we can call C# code behind from jQuery.



 

41. What is the use of jQuery.data() method?

Ans:

jQuery data method is used to associate data with DOM nodes and JavaScript objects. This method will make a code very concise and neat.

42. What is the difference between onload() and document.ready()?

Ans:

In a page, we can have only one onload function but we can have more than one document.ready function. Document.ready function is called when DOM is loaded but onload function is called when DOM and images are loaded on the page.

43. What is the use of jQuery each function?

Ans:

jQuery each function is used to loop through each and every element of the target jQuery object. It is also useful for multi element DOM, looping arrays and object properties.

44. How method can be called inside code behind using jQuery?

Ans:

$.ajax can be called and by declaring WebMethod inside code behind using jQuery.

45. Which is the fastest selector in jQuery?

Ans:

ID and Element are the fastest selectors in jQuery.

46. What is the slowest selector in jQuery?

Ans:

Class selectors are the slowest selectors in jQuery.

47. Where jQuery code is getting executed?

Ans:

jQuery code is getting executed on a client browser.

48. What is the method used to define the specific character in place of $ sign?

Ans:

‘NoConflict’ method is used to reference a jQuery and save it in a variable. That variable can be used instead of Sign.

49. Why jQuery is better than JavaScript?

Ans:

jQuery is a library used for developing Ajax application and it helps to write the code clean and concise. It also handles events, animation and Ajax support applications.

50. What are the types of selectors in jQuery?

Ans:

There are three types of selectors in jQuery:

  • CSS Selector
  • XPath Selector
  • Custom Selector



 

51. Explain what the following code will do: $( “div#first, div.first, ol#items > [name$=’first’]” )

Ans:

This code performs a query to retrieve any <div> element with the id first, plus all <div> elements with the class first, plusall elements which are children of the <ol id=”items”> element and whose name attribute ends with the string “first”. This is an example of using multiple selectors at once. The function will return a jQuery object containing the results of the query.

52. The code below is for an application that requires defining a click handler for all buttons on the page, including those buttons that may be added later dynamically.
What is wrong with this code, and how can it be fixed to work properly even with buttons that are added later dynamically?

// define the click handler for all buttons
$( "button" ).bind( "click", function() {
alert( "Button Clicked!" )
});
/* ... some time later ... */
// dynamically add another button to the page
$( "html" ).append( "<button>Click Alert !</button>" );

Ans:

The button that is added dynamically after the call to bind() will not have the click handler attached. This is because the bind()method only attaches handlers to elements that exist at the time the call to bind() is made.
This problem is solved with functions that use “event bubbling” to match events on both current and future elements. In the past, this was done by replacing bind() with live(). live() was deprecated in jQuery 1.7 though. delegate() works similarly to live() but also provides control over how far an event must bubble up the DOM.
However, the recommended method is to use on(), which can behave like bind(), live(), or delegate() depending on syntax. The following code attaches the handler to all current and future buttons:

// define the click handler for all buttons
$( document ).on( "click", "button", function() {
alert( "Button Clicked!" )
});

/* … some time later … */

// dynamically add another button to the page
$( “html” ).append( “” );

53. What’s the deal with the $ in jQuery? What is it and what does it mean?
Also, how can jQuery be used in conjunction with another JavaScript library that also uses $ for naming? Bonus credit if you can provide two answers.

Ans:

Since $ has no special meaning in JavaScript, it is free to be used in object naming. In jQuery, it is simply used as an alias for the jQuery object and jQuery() function.
However, jQuery has no monopoly on use of $, so you may encounter situations where you want to use it in conjunction with another JS library that also uses $, which would therefore result in a naming conflict. jQuery provides the jQuery.noConflict()method for just this reason. Calling this method makes it necessary to use the underlying name jQuery instead in subequent references to jQuery and its functions.
Here’s an example from the jQuery documentation:

<script src="other_lib.js"></script>
<script src="jquery.js"></script>
<script>
$.noConflict();
// Code that uses other library's $ can follow here.
</script>

Alternatively, you can also use a closure instead of the $.noConflict() method; e.g.:

(function ($) {
// Code in which we know exactly what the meaning of $ is
} (jQuery));

54. Given the following HTML:

<div id="expander"></div>

and the following CSS:

div#expander{
width: 100px;
height: 100px;
background-color: blue;
}

Write code in jQuery to animate the #expander div, expanding it from 100 x 100 pixels to 200 x 200 pixels over the course of three seconds.

Ans:

This could be done in jQuery as follows:

$( "#expander" ).animate(
{
width: "200px",
height: "200px",
},
3000 );

55. What is method chaining in jQuery? Provide an example. What advantages does it offer?

Ans:

Method chaining is a feature of jQuery that allows several methods to be executed on a jQuery selection in sequence in a single code statement. For example, the following snippets of code are equivalent:
Without chaining:

$( "button#play-movie" ).on( "click", playMovie );
$( "button#play-movie" ).css( "background-color", "orange" );
$( "button#play-movie" ).show();

With chaining:

$( "button#play-movie" ).on( "click", playMovie )
.css( "background-color", "orange" )
.show();

Notice that with chaining, the button only needs to be selected one time, whereas without chaining, jQuery must search the whole DOM and find the button before each method is applied. Thus, in addition to yielding more concise code, method chaining in jQuery offers a potentially powerful performance advantage.

Note: To be entirely precise, it should be noted that method chaining in jQuery is not the only way to avoid repetitively searching the entire DOM. One could also set a variable equal to the initial DOM search results (i.e., in the above example, one could set a variable equal to $( “button#play-movie” and then call the on(), css(), and show() methods on that variable). But that said, chaining is still the more concise and efficient option and doesn’t require caching the result in a local variable.

56. Explain what the following code does:
$( “div” ).css( “width”, “300px” ).add( “p” ).css( “background-color”, “blue” );

Ans:

This code uses method chaining to accomplish a couple of things. First, it selects all the <div> elements and changes their CSS width to 300px. Then, it adds all the <p> elements to the current selection, so it can finally change the CSS background color for both the <div> and <p> elements to blue.

57. What is the difference between jQuery.get() and jQuery.ajax()?

Ans:

jQuery.ajax() is the all-encompassing Ajax request method provided by jQuery. It allows for the creation of highly-customized Ajax requests, with options for how long to wait for a response, how to handle a failure, whether the request is blocking (synchronous) or non-blocking (asynchronous), what format to request for the response, and many more options.
jQuery.get() is a shortcut method that uses jQuery.ajax() under the hood, to create an Ajax request that is typical for simple retrieval of information. Other pre-built Ajax requests are provided by jQuery, such as jQuery.post(), jQuery.getScript(), and jQuery.getJSON().

58. Which of the two lines of code below is more efficient? Explain your answer.
document.getElementById( “logo” );
or
$( “#logo” );

Ans:

The first line of code, which is pure JavaScript without jQuery, is more efficient and faster. Executing the second line of code, which is jQuery, will trigger a call to the JavaScript version.
jQuery is built on top of JavaScript and uses its methods under the hood to make DOM manipulation easier, at the cost of some performance overhead. It is a good idea to remember that jQuery is not always better than plain old JavaScript. Always consider whether using jQuery really provides a useful advantage for your project.

59. Explain and contrast the usage of event.preventDefault() and event.stopPropagation(). Provide an example.

Ans:

event.stopPropagation() stops an event from bubbling up the event chain, whereas event.preventDefault() only precludes the browser’s default action on that event from occurring, but the event still propogates up the event chain.
For example, consider the following code snippet:
// in this example, ‘foo’ is a div containing button ‘bar’

$("#foo").click(function() {
// mouse click on div 'foo'
});

$(“#bar”).click(function(e) {
// mouse click on button ‘bar’
e.stopPropagation();
});

Due to the call to stopPropagation() in the button’s click handler, the event never propogates to the div so its click handler never fires. It effectively stops parent elements from knowing about an event on their children.
In contrast, if you replaced the above call to stopPropagation() with a call to preventDefault(), only the browser’s default action would be precluded, but the div’s click handler would still fire.

(Note: Although the stopPropagation() and preventDefault() methods are mostly used in jQuery event handling implementations, they apply to plain JavaScript as well.)

60. What selector would I use to query for all elements with an ID that ends with a particular string? Also, how would I modify the selector to retrieve only elements whose IDs end with that same string? Provide an example.

Ans:

Let’s say you want to retrieve all elements whose IDs end with “txtTitle”. This could be done using the following selector:
$(“[id$=’txtTitle’]”)

To retrieve only

elements whose IDs end with “txtTitle”, the selector would be:
$(“div[id$=’txtTitle’]”)


 

61. What is accomplished by returning false from (a) a jQuery event handler, (b) a regular JavaScript onclick event handler for an anchor tag, and (c) a regular JavaScript onclick event handler for a non-anchor tag (e.g., a div, button, etc.)?

Ans:

(a) Returning false from a jQuery event handler is effectively the same as calling both preventDefault() and stopPropagation() on the passed jQuery event object.
(b) Returning false from a regular JavaScript onclick event handler for an anchor tag prevents the browser from navigating to the link address and stops the event from propagating through the DOM.
(c) Returning false from a regular JavaScript onclick event handler for a non-anchor tag (e.g., a div, button, etc.) has absolutely no effect.

62. What is meant by a “deep copy”?

Ans:

The .clone() method performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as their descendant elements and text nodes.

63. What is normally not included in the cloned copy? How can some of this behavior be controlled?

Ans:

Normally:
Objects and arrays within element data are not copied and will continue to be shared between the cloned element and the original element. To deep copy all data, you must copy each one “manually”.
Any event handlers bound to the original element are not copied to the clone.
Setting the optional withDataAndEvents parameter to true makes copies of all of the event handlers as well, bound to the new copy of the element.
As of jQuery 1.4, all element data (attached by the .data() method) is also copied to the new copy.
As of jQuery 1.5, withDataAndEvents can be optionally enhanced with deepWithDataAndEvents to copy the events and data for all children of the cloned element.

64. What is a potential “gotcha” when using the clone() method? (HINT: What is an element attribute that you would generally not want to clone?)

Ans:

Using .clone() has the potentially problematic side-effect of producing elements with duplicate id attributes, which are supposed to be unique. Therefore, when cloning an element with an id attribute, it’s important to remember to modify the id of the clone, before inserting it into the DOM.

65. Explain the .promise() method in jQuery, including how and why it would be used.
Consider the code snippet below. If there are 5

elements on the page, what will be the difference between the start and end times displayed?
function getMinsSecs() {
var dt = new Date();
return dt.getMinutes()+":"+dt.getSeconds();
}
$( "input" ).on( "click", function() {
$( "p" ).append( "Start time: " + getMinsSecs() + "
" );
$( "div" ).each(function( i ) {
$( this ).fadeOut( 1000 * ( i * 2 ) );
});
$( "div" ).promise().done(function() {
$( "p" ).append( "End time: " + getMinsSecs() + "
" );
});
});

Ans:

The .promise() method returns a dynamically generated Promise that is resolved once all actions of a certain type bound to the collection, queued or not, have ended.
It takes two optional arguments:
type – By default, type is “fx”, which means that the returned Promise is resolved when all animations of the selected elements have completed.
target – If a target object is specified, .promise() will attach to it and then return this object rather than create a new one.
In the code sample provided, the difference between the start and end times displayed will be 10 seconds. This is because .promise() will wait for all

animations (in this case, all fadeOut() calls) to complete, the last of which will complete 10 seconds (i.e., 5 * 2 seconds) after the animation starts.

66. What is the proper way in jQuery to remove an element from the DOM before its Promise is resolved?

Ans:

A returned Promise in jQuery is linked to a Deferred object stored on the .data() for an element. Since the .remove() method removes the element’s data as well as the element itself, it will prevent any of the element’s unresolved Promises from resolving.
Therefore, if it is necessary to remove an element from the DOM before its Promise is resolved, use .detach() instead and follow with .removeData() after resolution.

67. Explain the difference between the .detach() and .remove() methods in jQuery.

Ans:

The .detach() and .remove() methods are the same, except that .detach() retains all jQuery data associated with the removed elements and .remove() does not. .detach() is therefore useful when removed elements may need to be reinserted into the DOM at a later time.

68. What’s the difference between document.ready() and window.onload()?

Ans:

The document.ready() event occurs when all HTML documents have been loaded, but window.onload() occurs when all content (including images) has been loaded. So generally the document.ready() event fires first.

69. What’s the difference between prop() and attr()?

Ans:

Both prop() and attr() are used to get or set the value of the specified property of an element attribute, but attr() returns the default value of a property whereas prop() returns the current value.

70. What is $() in jQuery library?

Ans:

The $() function is an alias of jQuery() function, at first it looks weird and makes jQuery code cryptic, but once you get used to it, you will love it’s brevity. $() function is used to wrap any object into jQuery object, which then allows you to call various method defined jQuery object. You can even pass a selector string to $() function, and it will return jQuery object containing an array of all matched DOM elements. I have seen this jQuery asked several times, despite it’s quite basic, it is used to differentiate between developer who knows jQuery or not.



 

71. You have five div element in your page? How do you select them using jQuery?

Ans:

Another fundamental jQuery question based on selector. jQuery supports different kinds of selector e.g. ID selector, class selector and tag selector. Since in this question nothing has been mentioned about ID and class, you can use tag selector to select all div elements. jQuery code : $(“div”), will return a jQuery object contain all five div tags. For more detailed answer, see the article.

72. Difference between ID selector and class selector in jQuery?

Ans:

If you have used CSS, then you might know the difference between ID and class selector, It’s same with jQuery. ID selector uses ID e.g. #element1 to select element, while class selector uses CSS class to select elements. When you just need to select only one element, use ID selector, while if you want to select a group of element, having same CSS class than use class selector. There is good chance that, Interview will ask you to write code using ID and class selector. Following jQuery code uses ID and class selectors :

$(“#LoginTextBox”) — Returns element wrapped as jQuery object with id=”LoginTextBox”
$(“.active”) — Returns all elements with CSS class active.

From syntax perspective, as you can see, another difference between ID and class selector is that former uses “#” and later uses “.” character.

73. How do you hide an image on a button click using jQuery?

Ans:

This jQuery interview question is based on event handling. jQuery provides good support for handling events like button click. You can use following code to hide an image, found using Id or class. What you need to know is hide() method and how to setup an even handler for button, to handle clicks, you can use following jQuery code to do that :

$(“#ButtonToClick”).click(function(){
$(“#ImageToHide”).hide();
});

74. How do you find all selected options of HTML select tag?

Ans:

This is one of the tricky jQuery question on Interviews. It’s still a basic, but don’t expect every jQuery beginners to know about this. You can use following jQuery selector to retrieve all selected options of <select> tag with multiple=true :

$('[name=NameOfSelectedTag] :selected')

This code uses attribute selector in combination of :selected selector, which returns only selected options. You can tweak this and instead of name, you can even use id attribute to retrieve <select> tag.

75. What is each() function in jQuery? How do you use it?

Ans:

each() function is like Iterator in Java, it allows you to iterate over a set of elements. You can pass a function to each() method, which will be executed for each element from the jQuery object, on which it has been called. This question sometime asked as follow-up of previous question e.g. how to show all selected options in alert box. We can use above selector code to find all selected option and than further can use each() method to print them in alert box, one by one, as shown below:
$(‘[name=NameOfSelectedTag] :selected’).each(function(selected){
alert($(selected).text());
});
text() method returns text for that option.

76. How do you add an HTML element in DOM tree?

Ans:

You can use jQuery method appendTo() to add an HTML element in DOM tree. This is one of the many DOM manipulation method jQuery provides. You can add an existing element or a new HTML element, appendTo() add that method in the end of a particular DOM element.

77. Can you write jQuery code to select all links, which is inside paragraphs?

Ans:

Another jQuery interview question based on selector. This also required to write jQuery one liner, like many other questions. you can use following jQuery snippet to select all links ( tag) nested inside paragraphs (<a> tag) nested inside paragraphs (<p> tag).

78. Difference between $(this) and this keyword in jQuery?

Ans:

Could be a tricky questions for many jQuery beginners, but indeed it’s simplest one. $(this) returns a jQuery object, on which you can call several jQuery methods e.g. text() to retrieve text, val() to retrieve value etc, while this represent current element, and it’s one of the JavaScript keyword to denote current DOM element in a context. You can not call jQuery method on this, until it’s wrapped using $() function i.e. $(this).

79. How do you retrieve attribute of an HTML tag using jQuery e.g. href of links?

Ans:

attr() method is used to retrieve value of an attribute of any HTML element. You first need to select all links or specified links using jQuery selector and than you can apply attr() method to get value of there href attribute. Below code will find all links from a page and return href value :
$(“a”).each(function(){
alert($(this).attr(‘href’));
});

80. How do you set attribute using jQuery?

Ans:

One more follow-up question of previous jQuery question, attr() method is overload like many other methods in JQuery. If you call attr() method with value e.g. attr(name, value), where name is the name of attribute and value is the new value.




 

81. What is difference between detach() and remove() method in jQuery?

Ans:

Though both detach() and remove() method is used to remove a DOM element,Main difference between them is that detach() keep track of the last element detached, so that it can be reattached, while remove() method does keep reference of last removed method. This is one of the many jQuery interview question from DOM manipulation. You can also take a look on appendTo() for adding element into DOM.

82. How do you add and remove CSS classes to an element using jQuery?

Ans:

By using addClass() and removeClass() jQuery methods. This can be very handy, while dynamically changing class of elements e.g. marking them inactive or active and using class “.active” etc.

83. What is main advantage of loading jQuery library using CDN?

Ans:

This is slightly advanced jQuery question, and don’t expect that jQuery beginners can answer that. Well, apart from many advantages including reducing server bandwidth and faster download, one of the most important is that, if browser has already downloaded same jQuery version from same CDN, than it won’t download it again. Since now days, almost many public websites use jQuery for user interaction and animation, there is very good chance that browser already have jQuery library downloaded

84. What is difference between jQuery.get() and jQuery.ajax() method?

Ans:

ajax() method is more powerful and configurable, allows you to specify how long to wait and how to handle error, get() is a specialization to over ajax just to retrieve some data.

85. What is method chaining in jQuery? what is benefit of using method chaining?

Ans:

Method chaining is calling another method in result of another method, it result in clean and concise code, single search over DOM so better performance.

86. What happen if you return false from a jQuery event handler?

Ans:

It used to stop the event bubbling up

87. What is jQuery Selectors? Give some examples.

Ans:

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

Select elements by tag name
Example : $(div)
It will select all the div elements in the document.

Select elements by ID
Example : $(“#xyzid”)
It will select single element that has an ID of xyzid.

Select elements by class
Example : $(“.xyzclass”)
It will select all the elements having class xyzclass.

88. How can we give face effect in jQuery?

Ans:

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

89. Explain the animate function.

Ans:

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

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

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

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

Ans:

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


 

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

Ans:

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.

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

Ans:

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

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

Ans:

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

94. Explain the each() function.

Ans:

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.

95. Explain slideToggle() effect.

Ans:

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

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

Ans:

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.

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

Ans:

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”

98. What is jQuery.holdReady() function?

Ans:

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

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

Ans:

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

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

Ans:

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

1. Create cookie
$.dough(“cookie_name”, “cookie_value”);

2. Read Cookie
$.dough(“cookie_name”);

3. Delete cookie
$.dough(“cookie_name”, “remove”);



 

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

Ans:

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.

102. What is Chaining in jQuery?

Ans:

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.

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

Ans:

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

104. What is difference between prop and attr?

Ans:

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’

105. How to always reference latest version of jQuery?

Ans:

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.

106. What is resize() function in jQuery?

Ans:

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

107. How can jquery library be added to pages? Write a basic jquery code?

Ans:

The jquery library is a collection of all the jquery methods. It is stored in the form of a single java script file. Th format of adding a jquery file to an html page is:

 
<head>
<script type=”text/javascript” src”jquery.js”></script>
</head>

An example of a javascript that will hide all the <p> elements in the page.

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("button").click(function()
{
$("p").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body>
</html>

108. What are the types of selectors that are used in jquery? Give examples.

Ans:

Jquery enables the user to select specifically the element that is to be effected. jquery allows the user to select in the following ways:
jquery element selectors : With the use of css selectors the users can select the elements of an html document.

For ex.
$(“p”) will select all the

elements.
$(“p.intro”) will select all

elements with class=”intro” defined in them.
$(“p#demo”) this will select all

elements with id=”demo”.

jquery attribute selectors: the xpath expressions are used by jquery to select elements of an html document with defined attributes.

For ex.
$(“[href]”) is used to select all elements which have an href attribute.
$(“[href$=’.jpg’]”) can select all elements with an href attribute which will end with “.jpg”.

109. How can images be made to appear scrolling one over another?

Ans:

Jquery provides the user with the ability to change the attributes of a property dynamically. The jquery slide method can be used to change the height of elements gradually. This can be used to give the scroll effect of an image over image.
The jquery comprises of the following slide methods:

$(selector).slideDown(speed,callback)
$(selector).slideUp(speed,callback)
$(selector).slideToggle(speed,callback)

The speed parameter is used to effect the speed of change of the jquery. The parameters for it can be slow, fast , normal and time in milliseconds. The parameter of callback is used to refer to the name of the function to be executed once the completion of function occurs.

110. What are the various ajax functions?

Ans:

Ajax allows the user to exchange data with a server and update parts of a page without reloading the entire page. Some of the functions of ajax are as follows:

$.ajax() : This is considered to be the most low level and basic of functions. It is used to send requests . This function can be performed without a selector.

$.ajaxSetup() : This function is used to define and set the options for various ajax calls.

For ex.

$.ajaxSetup({
"type":"POST",
"url":"ajax.php",
"success":function(data)
{
$("#bar")
.css("background","yellow")
.html(data);
}
});

Shorthand ajax methods : They comprise of simply the wrapper function that call $.ajax() with certain parameters already set.

$.getJSON() : This is a special type of shorthand function which is used to accept the url to which the requests are sent. Also optional data and optional callback functions are possible in such functions.




 

111. What are the guidelines for an application to follow the principles of progressive enhancement.

Ans:

Progressive enhancement is web development technique that would allow the application to be accessible to any computer with any Internet connection. For an application to work on the principles of progressive enhancement the following rules / guidelines must be met:

The basic content must be available to all browsers with any type of Internet connections.
The basic functionalities of an application must be working in all browsers.
The application will not override any of the user specified browser settings.
The css files are linked externally to control the look and feel of the page.
The javascripts should also be externally linked as it can enhance the user experience.

112. How can events be prevented to work after an ajax request?

Ans:

There are two ways to handle this issue:

Use of event delegation : The event delegation technique works on principle by exploiting the event bubbling. It uses event bubbling to capture the events on elements which are present anywhere in the domain object model. In jquery the user can make use of the live and die methods for the events delegation which contains a subset of event types.

For ex. Handling even delegation, handling of clicks on any element:
$(‘#mydiv’).click(function(e)
{
if( $(e.target).is(‘a’) )
fn.call(e.target,e);
});
$(‘#mydiv’).load(‘my.html’)

Event rebinding usage : When this method is used it requires the user to call the bind method and the added new elements.

For ex.
$(‘a’).click(fn);
$(‘#mydiv’).load(‘my.html’,function()
{
$(‘#mydiv a’).click(fn);
});

113. How can an element be checked if it contains a specific class?

Ans:

The hasClass method defined can be used to check if an element actually contains the specified class.

For ex : usage of the hasClass:

$(“div”).click(function()
{
if ( $(this).hasClass(“protected”))
$(this)
.animate({ left: -10 })
.animate({ left: 10 })
.animate({ left: -10 })
.animate({ left: 10 })
.animate({ left: 0 });
});

The is() method can also be used with a selector for a more advanced level of matching.
For ex.
if ( $(‘#myDiv’).is(‘.pretty.awesome’) )
$(‘#myDiv’).show();

This method can be used to test various other things, such as it could be used to detect if the specified element is hidden or not.

114. Why is the block display style used for animations?

Ans:

In html only the block level elements can have custom heights and widths. So when a user defines an animation method for usage such as show, hide, slide up etc the display css property of the block being animated is set to display block style. On completion of the animation the display style of the block would be changed to its original value. This procedure does not work properly for inline elements and the following workarounds can be applied to it:

If the user wants the element to remain inline and only want to animate it in and out he can use the fadein and fadeout animation instead of using the show method.
The user can also use a block level element with float to make the element appear inline with the rest of the content around it.

115. What are the approaches of extracting a query string with regular expressions?

Ans:

There are two approaches of doing so:

String based approach : This is the simple way of extracting the information of a query string using the string-based replacement technique. This method makes use of the .replace() method to function.
For ex :
var data = string.replace(“http://localhost/view.php?”, “”);

The above code works fine for the string based approach but has some flexibility issues. It cannot deal effectively with domain name and file name changes.

Regular expression approach : They are a powerful pattern matching tool available in modern programming languages. For the extraction of a query string a pattern would have to be used which looks for a question mark in the string. Once it does it returns everything after it. The regular expression in JS are delimited using the forward slashes at the end of an expression.

116. How does jquery store data related to an element?

Ans:

In plain java scripts the information about an element can be stored by adding a domain object model property to the element. This results in memory leak problems in certain browsers. In jquery the user does not has to worry about memory management issues.

For ex : Storing and retrieving data related to an element:
$(‘#myDiv’).data(‘keyName’, { foo : ‘bar’ });
$(‘#myDiv’).data(‘keyName’); // { foo : ‘bar’ }

Jquery allows the user to store any kind of information on an element. The $.fn.data is used the most to store data related to an element.

For ex : Storing of relationship between elements with the use of $.fn.data :
$(‘#myList li’).each(function()
{
var $li = $(this), $div = $li.find(‘div.content’);
$li.data(‘contentDiv’, $div);
});
// later, the user is not required to look for the div again;
// the data can simply be read from the list items data;
var $firstLi = $(‘#myList li:first’);
$firstLi.data(‘contentDiv’).html(‘new content’);

117. Explain the common methods of sending a request to a server.

Ans:

The two most common methods of sending a request to a server are :

1. GET method : The get method is mostly used for non destructive operations. These operations get data from the server and does not change the data on it. A good example of the application of the search query to a server. In most of the cases GET will send all of the data to be sent in the form of a query string.
2. POST method : The POST method is primarily used for destructive operations. These operations can change the data on a server. A good example is a user saving an entry on a site will get the POST request. These requests are not cached by the browser. A query can be a part of a url but any data that is to be sent is done separately as post data.

118. Create a plugin that would add and remove a class on hover.

Ans:

The plugin can be considered to be simply a new method that can be used by a user to extend the prototype object of a jquery. A plugin performs some actions on a collection of elements. Each method that comes with the jquery core can be considered to be a plugin.

The code for creating a plugin that would add and remove a class on hover would be as follows:

(function($)
{
$.fn.hoverClass = function(c)
{
return this.hover(
function() { $(this).toggleClass(c); }
);
};
})(jQuery);

// using the plugin
$(‘li’).hoverClass(‘hover’);

119. Explain the use of the .pushStack() method.

Ans:

The pushStack() method works by accepting an array of DOM elements and pushes them into a stack. This is done so that call to methods like .end() and .andSelf are able to behave correctly. The jquery internally uses this method to keep track of all the previous collections of jquery while using a chain traversing method. Good examples of such methods could be .parents() and .filter().

For ex :

// select some divs
$('div.container')
// find some spans inside those divs and add a class to them
.find('span').addClass('baby')
// pop those spans off the "stack",
// returning to the previous collection (div.container)
.end()
// add a class to the parent of each div.container
.parent().addClass('daddy');

120. How is the deferred method in jquery important in relation to animate method?

Ans:

The .animate() method is used to create animations with other shorthands using it. The queue() method can be used to link together multiple animation methods to create an unique effect. These methods are effective when all the data is available locally and all the methods are executed on as single system only. In case the user wants to use the animation methods on a data that resides on the server and wants to handle at a single go the user can make used of the .deferred method.

For ex :

var my$ = $.sub();
my$.fn.animate = function( props, speed, easing, callback )
{
var options = speed && typeof speed === "object" ?
jQuery.extend({}, speed) :
{
complete: callback || !callback && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: callback && easing || easing &&
!jQuery.isFunction(easing) && easing
};
var dfd = my$.Deferred(),
complete = options.complete,
count = this.length;
options.complete = function()
{
complete && complete.call( this );
if ( !--count )
{
dfd.resolve();
}
}
};

 

121. Explain some of the key concepts of good code organization patterns.

Ans:

Some of the key concepts that should be followed while:

The codes should always be divided into specific units of functionality. They can be divided into modules , services etc. This concept is also known as encapsulation.
Use inheritance techniques to avoid rewriting a code again and again.
The jquery is dom centric in nature but not all applications are such in nature. All funtionalities should not have a dom representation.
All the units of functionality should be existing in a loosely coupled state. This implies that a module can exist independently. Also the communication between the units should be possible and should be handled using a messaging system for example custom events.

122. How can related code be encapsulated? Give example.

Ans:

The object literal is one of the simplest ways that the user can encapsulate related code together. It helps by removing any anonymous functions from the users code. It can also be used to centralize configuration options.
For ex : An object literal being implemented

var myFeature = 
{
myProperty : 'hello',
myMethod : function()
{
console.log(myFeature.myProperty);
},
init : function(settings)
{
m2yFeature.settings = settings;
},
readSettings : function()
{
console.log(myFeature.settings);
}
};
myFeature.myProperty; // 'hello'
myFeature.myMethod(); // logs 'hello'
myFeature.init({ foo : 'bar' });
myFeature.readSettings(); // logs { foo : 'bar' }

123. Write a code for the implementation of a module pattern.

Ans:

The object literal does not provide any privacy for the methods or properties. The module pattern allows the user to offer privacy to functions and variables. It can be used to set to expose limited API.

For ex : The module pattern code:

var feature =(function() 
{
var privateThing = 'secret',
publicThing = 'not secret',
changePrivateThing = function()
{
privateThing = 'super secret';
},
sayPrivateThing = function()
{
console.log(privateThing);
changePrivateThing();
};
return
{
publicThing : publicThing,
sayPrivateThing : sayPrivateThing
}
})();
feature.publicThing; // 'not secret'
feature.sayPrivateThing();

124. Write the code to define a RequireJs module with its dependencies.

Ans:

The RequireJS is a dependency management tool that can be used by the user to manage script modules. It can be used to load scripts once a page has been loaded. This helps in evenly distributing the downloads.

For ex : RequireJS module with dependencies defined:

require.def("my/shirt",
["my/cart", "my/inventory"],
function(cart, inventory)
{
//return an object to define the "my/shirt" module.
return
{
color: "blue",
size: "large"
addToCart: function()
{
inventory.decrement(this);
cart.add(this);
}
}
}
);

125. Explain the use of the $.fn.bind and $.fn.trigger.

Ans:

Both the $.fn.bind and $.fn.triggers are two important jquery methods. They are primarily used with custom events.

$.fn.bind : This method accepts an event type and an event handling function as an argument for itself. This method can also accept event-related data as a second argument.
$.fn.trigger : This method can accept an event type as an argument. It can also take an array of values.
Ex : Depicting the usage of $.fn.bind and $.fn.triggers using custom data in both the cases:

$(document).bind('myCustomEvent', { foo : 'bar' },
function(e, arg1, arg2)
{
console.log(e.data.foo); // 'bar'
console.log(arg1); // 'bim'
console.log(arg2); // 'baz'
});
$(document).trigger('myCustomEvent', [ 'bim', 'baz' ]);

126. What is the Struts2 jQuery plugin and its advantages.

Ans:

The struts2 jquery plugin is used to:
It provides the user with an easy integration of ajax and widgets.
It reduces the number of code to be written by a coder.

For ex :

<div id="result">Result Div</div>
<s:url id="ajax" value="/ajax1.action"/>
<sj:a id="ajaxlink" href="%{ajax}" indicator="indicator" targets="result" effect="highlight">
Run AJAX Action
</sj:a>
<img id="indicator" src="images/indicator.gif" alt="Loading..." style="display:none"/>

The advantages of using it are:
It reduces the number of code to be written dramatically.
It also supports ajax form validation.
The code becomes much easier to read and hence prevents errors from occurring and is easy to debug.