jQuery

81 jQuery Interview Questions and Answers – The ULTIMATE List

Without a doubt, jQuery has given a much needed boost to JavaScript, a language so useful but equally underrated at times. Before jQuery came into the picture, we used to write lengthy JavaScript code not just for bigger but even for smaller functionality. That code was at times both difficult to read and maintain. Having written JavaScript before using this excellent library, we realized the true power of jQuery.

This article has been designed specially to get you acquainted with the nature of questions you may encounter during your interview. Normally questions start with some basic concept of the subject and later continue based on further discussion and what the candidate answers. I hope these questions serve as a quick revision to provide strength to your skills.
 

1. jQuery: An Overview

1.1 What is jQuery?

JQuery is a cross-browser lightweight JavaScript library. In simple words jQuery has been designed to make navigation to any element easier, or adding/invoking event handlers on your HTML page and also simplify the way you access the elements in your web pages, provide help in working with client-side events, enable visual effects like animation, and make it easier to use Ajax in your applications.

A quick look at what is available in jQuery:

• Cross-browser support and detection.
• AJAX functions
• CSS functions
• DOM manipulation
• DOM transversal
• Attribute manipulation
• Event detection and handling.
• JavaScript animation
• Hundreds of plugins for pre-built user interfaces, advanced animations, form validation, etc.
• Expandable functionality using custom plugins.

jquery-qa-1
jQuery – Write Less, Do More!

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.

1.2 Why you should be using jQuery?

Based on the manipulation of the HTML DOM (Document Object Model) and designed to simplify the client-side scripting of HTML, jQuery incorporates parts of HTML and CSS. Thousands of companies and individuals are on the jQuery bandwagon, and you should be, too.

1. jQuery promotes simplicity

Developers find jQuery intuitive and easy to learn — this library is built on shorter, simpler code, after all. With simple syntax and open coding standards, developers can shorten the time it takes to deploy an application or site.

In addition, developers don’t have to be experts in programming or Web design to create great styles for their sites. Any developer who has spent hours coding and testing CSS files will surely appreciate the simple implementation that jQuery brings to the table.

2. jQuery elements display even when JavaScript is disabled

If Adobe Flash isn’t installed on any given browser, certain parts of the page may render incorrectly, if they render at all. This is not only unpleasant for the user; it forces developers to spend extra time coding for the browsers that lack the Flash plug-in, which adds to development time.

Not so with jQuery. Manipulating the HTML DOM has become the most widely accepted practice of manipulating a Web page so content will be rendered even if JavaScript is disabled in the browser. Since the HTML DOM is always present, there’s no more worrying about browser settings either.

3. jQuery pages load faster

Google and other search engines using page load time as one of the many factors affecting SEO. For this, and many other reasons, every developer should strive to make code as light and concise as possible.

The best way to do this is to reduce the size of your code. If your site is coded with an HTML and CSS base, you can easily make uniform adjustments to your code that will reduce the size. Like CSS, jQuery files are generally stored separately from the Web page itself. This lets developers make modifications across the entire site through one central repository instead of search through folder structures. This is a core benefit of CSS coding, and it is a proven success.

In addition, jQuery gives you the option of loading div tags only when you need them. If you are taking measures to improve the speed of your website, then you may consider loading only the necessary div tags needed for your page load event. This way, you can display only what a user needs to see right away and have the rest of your division elements load as they are needed.

Moreover

• The price is right. The jQuery library is free.
• It’s light. Since jQuery pushes content to the client, it therefore reduces the wait time for server response.
• It works anywhere. HTML5 is cross-browser compatible-it will work on any browser, mobile phone or tablet.
• There’s a low learning curve. Since it’s based on plain old JavaScript, developers can learn jQuery fast.
• Finally, jQuery is SEO friendly and CSS3 compliant.

1.3 jQuery Selectors

jQuery selectors are one of the most important parts of the jQuery library.

jQuery selectors allow you to select and manipulate HTML element(s). They are used to “find” (or select) HTML elements based on their id, classes, types, attributes, values of attributes and much more. It’s based on the existing CSS Selectors, and in addition, it has some own custom selectors. All selectors in jQuery start with the dollar sign and parentheses: $().

jquery-qa-3
An example of how a DOM element can be selected using jQuery!

• All Selectors

$("*") // find everything (Selectors return a pseudo-array of jQuery elements)

• Basic Selectors

1. By Tag:
$("h1") // <h1>Web Code Geeks</h1>

2. By ID:
$("#username") // Pete

3. By Class:
$(".menu")

• More Precise Selectors

$("div.main") // tag and class
$("table#main") // tag and id

• Combination of Selectors

$("#container, .f_left") // find by id + by class
$("h1, h2, h3, div.container") // multiple combination

• Hierarchy Selectors

$("table td") // descendants
$("tr > td") // children
$("label + input") // next
$("#content ~ div") // siblings

• Selection Index Filters

$("tr:first") // first element
$("tr:last") // last element
$("tr:lt(2)") // index less than
$("tr:gt(2)") // index gr. than
$("tr:eq(2)") // index equals

• Attribute Filters

$("div[id]") // has attribute
$("div[dir='rtl']") // equals to
$("div[id^='name]") // starts with
$("div[id$='main]") // ends with
$("a[href*='corner]") // contains

• Form Selectors

$("input:checkbox") // checkboxes
$("input:radio") // radio buttons
$(":button") // buttons
$(":text") // text inputs

To find out more about selectors, have a look at a more detailed article of ours about selectors here.

1.4 Basic Workflow

When you use JQuery, you typically follow these steps of action:

1. Wait for the page to be ready.
2. Select some HTML elements to modify.
3. Traverse the selected HTML elements.
4. Modify the HTML element attributes, CSS styles etc.
5. Add listener functions, e.g. click() or wait for a JQuery effect to finish etc.

// 1. Wait for the page to be ready.
$(document).ready(function() {


// 2. select the HTML element with id 'theDiv'
var theDiv = $('#theDiv');

// 3. since only 1 element was selected, no traversal is necessary

// 4. modify the HTML elements CSS attributes
theDiv.css("border", "1px solid black");

// 5. add a click-listener function to it.
theDiv.click(function() {
    $('#theDiv').show(300);
});
}

First the example calls jQuery’s $(document).ready() function, passing a function as parameter. The function passed as parameter is executed when the page is ready.

Second, the example selects the HTML element with the id “theDiv”. It does so by calling JQuery’s selection function, the $() function, passing a selection string as parameter.

Third, the example modifies the CSS attribute “border” of the HTML element. This is done by calling the css() function on the selected HTML element.

Fourth, the example adds a click listener function to the HTML element. It does so by calling the click() function on the selected element. When the HTML element is clicked, this function is executed.

1.5 The jQuery Family

You might get surprised, but jQuery is not alone. What that means is that along with the development of jQuery, there are also similar libraries initialized by the very same principles and core (Javascript) which are focused in more particular applications. The graphic below gives you a short introduction to each of them!

jquery-qa-2
The jQuery Family

2. Introductory Questions

1. What is jQuery?

jQuery is a 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. How JavaScript and jQuery are different?

jQuery is not a programming language but a well written JavaScript code. It is a library/framework built with Javascript. It is very popular because it (nearly universally) abstracts away cross-browser compatibility issues and it emphasises unobtrusive and callback-driven Javascript programming. Javascript is the core programming language.

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

Efficiency of web page increases when minimized version of jQuery is used. jQuery’s min.js file will be more than 50% less than the normal js file. Reduction in the file size makes the web page faster. They are both the same functionally but the .min one has all unnecessary characters removed in order to make the file size smaller.

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

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

5. What is $() in jQuery library?

The $() function is an alias of jQuery() function. $() 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.

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

Yes. It is possible using jQuery.noConflict() method. If we need to use another JavaScript library alongside jQuery, we return control of $ back to the other library with a call to $.noConflict(). Old references of $ are saved during jQuery initialization; noConflict() simply restores them.

Find out more on this method here.

7. What is AJAX in jQuery?

AJAX stands for “Asynchronous JavaScript and XML”. AJAX is about exchanging data with a server, without reloading the whole page. It is a technique for creating fast and dynamic web pages.
$.ajax () is JQuery’s core method for creating Ajax requests. Some jQuery AJAX methods are:

$.ajax() – Performs an async AJAX request.
$.get() – Loads data from a server using an AJAX HTTP GET request.
$.post() – Loads data from a server using an AJAX HTTP POST request.

8. What is $(document).ready() function? Why should you use it?

This is one of the most important and frequently asked jQuery Interview question. The ready() function is used to execute code when document is ready for manipulation. jQuery allows you to execute code, when DOM is fully loaded i.e. HTML has been parsed and DOM tree has been constructed. Main benefit of $(document).ready() function is that, it works in all browsers, jQuery handles cross browser difficulties for you.

Read more about the .ready() function here.

9. Tell the difference between JavaScript window.onload event and jQuery ready function?

Main difference between JavaScript onload event and jQuery ready function is that former not only waits for DOM to be created but also waits until all external resources are fully loaded including heavy images, audios and videos. If loading images and media content takes a lot of time, the user can experience significant delay on execution of code defined in window.onload event.

On the other hand jQuery ready() function only waits for the DOM tree, and does not wait for images or external resource loading, which means faster execution. Another advantage of using jQuery $(document).ready() is that you can use it multiple times in your page, and browser will execute them in the order they appear in HTML page, as opposed to onload technique, which can only be used for a single function. Given this benefits, it’s always better to use jQuery ready() function than JavaScript window.onload event.

10. What are jQuery Events?

Events are actions performed on a specific condition that are used for dynamic web pages. When we perform these actions on an HTML page, we can do whatever we want. We use some event handlers to perform the action. Some important handlers are bind(), unbind(), blur(), off(), hover(), on(), one(), ready(), trigger() etc.

11. What are jQuery plugins and what is the advantage of using a plugin?

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.

12. Mention some of the interactions available in the jQuery UI library.

We can use interactions for basic mouse-based behaviours to any element. Examples of Interactions are the following:

• Draggable
• Droppable
• Resizable
• Selectable
• Sortable

jquery-qa-4
jQuery UI Interactions Branch

3. Methods/Functions Questions

3.1 Similar Methods Comparison

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

All these methods .empty(), .remove() and .detach() are used for removing elements from DOM but they all are different.

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

.remove(): We use .remove() when we 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.

14. What is the difference between bind() and live() method in jQuery?

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.

$(document).ready(function () {   
   $('p').bind('click', function () {  
      alert("Example of Bind Method");  
      e.preventDefault();  
   });   
});  
Live() Method

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

$(document).ready(function() {  
    $('P').live('click', function() {  
        alert("Example of live method");  
        e.preventDefault();  
    });  
    $('body').append(''); });

15. A bigger picture comparison of .bind() vs .live() vs .delegate() vs .on()?

All these 4 jQuery methods are used for attaching events to selectors or elements. But they all are different from each other.

.bind(): This is the easiest and quick method to bind events. But the issue with bind() is that it doesn’t work for elements added dynamically that matches the same 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.

16. What is difference between prop and attr?

attr(): Gets the value of an attribute for the first element in the set of matched elements. Whereas, .prop(): will get the value of a property for the first element in the set of matched elements.

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

attr() gives you the value of an element as it was defined 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.

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

event.stopPropagation() allows other handlers on the same element to be executed, while event.stopImmediatePropagation() prevents every event from running. For example, see below jQuery code block:

$("p").click(function(event){
  event.stopImmediatePropagation();
});
$("p").click(function(event){
  // This function won't be executed
  $(this).css("background-color", "#f00");
}); 

If event.stopPropagation was used in previous example, then the next click event on p element which changes the css will fire, but in case event.stopImmediatePropagation(), the next p click event will not fire.

18. Explain width() vs css(‘width’)?

In jQuery, there are two way to change the width of an element.
One way is using .css(‘width’) and other way is using .width().

For example:

$(‘#mydiv’).css(‘width’,’300px’);
$(‘#mydiv’).width(100);

The difference in .css(‘width’) and .width() is the data type of value we specify or return from the both functions. In .css(‘width’) we have to add “px” in the width value while in .width() we don’t have to add. When you want to get the width of “mydiv” element then .css(‘width’) will return ‘300px’ while .width() will return only integer value 300.

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

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. You can check out this article to have a closer look at the .preventDefault() method.

20. What is the difference between calling stop(true,true) and finish method?

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.

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

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

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

eq() returns the element as a jQuery object. This method constructs a new jQuery object from one element within that set and returns it. That means that you can use jQuery functions on it.

get() returns a DOM element. The method retrieves the DOM elements matched by the jQuery object. But it is a DOM element and it is not a jQuery-wrapped object. So jQuery functions can’t be used.

3.2 Function Explanations

23. How do you implement animation functionality?

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.

$("btnClick").click(function(){
  $("#dvBox").animate({height:"100px"});
});

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

When we want to fetch siblings of every elements in the set of matched elements then we can use siblings() method. We filter the elements fetched by an optional selector.
The syntax is: .siblings([selector]) where “selector” is the selector expression which specify the matched elements.

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

Read more about the siblings() method here.

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

jQuery .data() is used to set/return arbitrary data to/from an element.
Syntax: jQuery.data(element, key, value) where:
– “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);

26. What is jQuery.holdReady() function?

jQuery .data() is used to set/return arbitrary data to/from an element.
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

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

27. What is the use of param() method?

The param() method is used to represent an array or an object in serialize manner.
While making an ajax request we can use these serialize values in the query strings of URL.
Syntax: $.param(object | array, boolValue).
For example:

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

28. Explain the resize() function in jQuery.

The resize() function is called whenever the browser size is changed. This event can be only used with $(window).
Syntax: .resize([event_data], handler(event_object)). For example:

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

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

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.

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

30. Explain the use of the .pushStack() method?

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 example:

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

3.3 What is the method we use to…?

31. In jQuery, the method we use to check whether an element is empty or not is..?

1. Using “:empt” selector
2. $.trim()
3. $.empty()
4. Both 1 & 2
5. All Above

The correct answer is: 4. Both 1 & 2.

32. In jQuery, the method we use to create a new ‘div’ element is..?

1. $(‘div’)
2. $(‘<div />’)
3. $.create(‘<div />’)
4. $.create(‘div’)
5. All Above

The correct answer is: 2. $(‘<div />’)

33. In jQuery, the method we use to stop the default action of the event from triggering is..?

1. event.stopPropagation()
2. event.preventDefault()
3. event.stopImmediatePropagation()
4. event.isDefaultPrevented()
5. All Above

The correct answer is: 2. event.preventDefault()

34. In jQuery, the method used to stop the running animation is..?

1. .stopAnimation()
2. .stopAnimate()
3. .stop()
4. None of the above
5. All Above

The correct answer is: 3. stop()

35. In jQuery, the method used to create a copy of the set of matched elements is..?

1. .copy()
2. .create()
3. .clode()
4. .createCopy()
5. All Above

The correct answer is: 3. clone().

Find out more about this method here.

4. Code Questions

4.1 Given Code Questions

36. Explain what the following code will do?

$( "div#first, div.first, ol#items > [name$='first']" )
Answer:

This code performs a query to retrieve any <div> element with the id first, plus all <div> elements with the class first, plus all 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.

37. 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( "" );
Answer:

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. Find out more about bind() in this article.

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

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

Answer:

This could be done in jQuery as follows:

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

39. What does the following code do?

$( "div" ).css( "width", "300px" ).add( "p" ).css( "background-color", "blue" );
Answer:

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.

Read more about using the .css() method in jQuery here.

40. Which of the two lines of code below is more efficient? Explain your answer?

document.getElementById( "logo" );

or

$( "#logo" );
Answer:

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.

4.2 Writing Code Questions

41. Consider the following situation:

I need to query all elements with an ID that ends with a particular string. Also, I’d like to modify the selector to retrieve only <div> elements whose IDs end with that same string? Provide an example showing how you would have done this.

Answer:

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 <div> elements whose IDs end with “txtTitle”, the selector would be:

$("div[id$='txtTitle']")

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

Answer:

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

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

Answer:

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.

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

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

Answer:

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. How do you attach a event to element which should be executed only once?

Answer:

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

5. AJAX Related Questions

5.1 General AJAX Questions

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

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.

47. What are the advantages of Ajax?

Following are the advantages of Ajax:
• Bandwidth utilization
• It saves memory when the data is fetched from the same page.
• More interactive
• Speeder retrieval of data

48. What about the disadvantages of Ajax?

• AJAX is dependent on Javascript. If there is some Javascript problem with the browser or in the OS, Ajax will not support.
• Ajax can be problematic in Search engines as it uses Javascript for most of its parts.
• Source code written in AJAX is easily human readable. There will be some security issues in Ajax.
• Debugging is difficult (not impossible)
• Increases size of the requests
• Slow and unreliable network connection.
• Problem with browser back button when using AJAX enabled pages.

49. What are the technologies used by Ajax?

AJAX uses following technologies:

• JavaScript
• XMLHttpRequest
• Document Object Model (DOM)
• Extensible HTML (XHTML)
• Cascading Style Sheets (CSS)

50. What Is the Format of an AJAX Request?

An AJAX request can be in any of the following formats:
• Text File
• HTML
• JSON object

51. How can you find out that an AJAX request has been completed?

We use the ReadyState property to check whether AJAX request has been completed. If the property is equal to four, then the request has been completed and data is available.

52. What is JSON in Ajax?

JSON is abbreviated as JavaScript Object Notation. JSON is a safe and reliable data interchange format in JavaScript, which is easy to understand for both users and machines.

53. How many types of triggers are present in update panel?

There are two types of triggers used in update panel:
• PostBackTrigger : This works as full postback and it cannot work asynchronously
• AsyncPostBackTrigger : Partial post back asynchronously

54. Which two methods are used for handling Cross-Domain Ajax Calls ?

Cross-domain means the ability to manually or automatically access or transfer data between two or more differing security domain
1) CROS (Cross-Origin Resource Sharing) : Works with all HTTP verbs and Mos modern web browsers. Provides better support for error handling than JSONP.
2) JSONP (JSON with padding) : It is only works HTTP GET verb and on legacy browsers.

55. When should AJAX NOT be used?

It would not be appropriate to use AJAX when the “answer/result” can be determinded by the client. Generally, the purpose of AJAX is to submit a short request to the server, and process the response in such a way as to add value to the currently displayed page.It would also not be appropriate to use AJAX when the magnitude of the response is such that it would be easier, and more clear to redisplay the page.

5.2 Technical AJAX Questions

56. How does AJAX work in simple steps?

This graphic would certainly give you a clearer idea!

jquery-qa-51
AJAX Communication Flow

57. How can AJAX response set a cookie?

Here are two solutions:
1. After getting response, Make another ajax call with request where you can set the cookie.
2. Before sending the ajax response, make the cookie in Server.
Use setcookie function, to set the cookie, like below:

$cookieValue='This is cookie value';
setcookie('name', $cookieValue, time() + 3600); 

58. How can you send data in an Ajax call?

You can send data in an AJAX call like this:

$.ajax({ 
    url: '/my/site/url',
    data: { name: "Arun", location: "Chandigarh" },
    type: 'post',
    success: function(result) {
              console.log(result);
}
});

59. How to submit entire form data with Ajax?

In that case, we can consider using serialize to gather form data and then pass it to a variable like so:

var formData = $('form#formId').serialize();
$.ajax({ 
        url: '/my/site',
         data: formData,
         type: 'post',
         success: function(result) {
         console.log(result);
   }
});

60. How to URLencode a string before sending in Ajax?

We use encodeURIComponent to encode a string. For Example:

 $.ajax({
        url: '/ajax/url',
        dataType: "json",
        data: name=encodeURIComponent('Test'),
        success: function(response) {
            if(response.success == 1){
                offWords = response.data;
            }
        },
        error: function(xhr, ajaxOptions, thrownError) {
        }
 });

61. Do AJAX requests retain PHP Session info, when calling multiple times?

Yes, PHP retains the session info over multiple ajax call. The duration of the php session depends on SESSION configuration.

62. How to update the image source, if the original image fails to load?

We use the onError attribute to update the image path, when failed to load.

<img alt="Image not found" onerror="this.src='show_img_when_original_failed.gif';" src="image.gif" />

63. Can you add headers in the AJAX Request?

Yes, you can do it like so:

$.ajax({
    type:"POST",
    beforeSend: function (request)
    {
        request.setRequestHeader("Header-Name", "Header Value");
    },
    url: "/ajax/url/",
    data: "name=web",
    processData: false,
    success: function(msg) {
        //Success
    }
    });

64. How to do synchronous AJAX requests?

Simply set the async=false in the AJAX call.

function getRemote() {
    return $.ajax({
        type: "GET",
        url: '/ajax/url',
        async: false
    }).responseText;
}

65. How can we send ajax request to another domain using JSONP?

JSONP is simple way to overcome XMLHttpRequest same domain policy. Using JSONP you can send the request to another domain. JSONP is “JSON with Padding“. In JSONP we include another domain URL with a parameter i.e callback. The callback’s value has a function name which must be present in your webpage.

<script>
function myCalllbackFunction(data){
  console.log(data);
} 
</script>

<script src="http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=myCalllbackFunction" type="text/javascript"></script>

Learn more about AJAX techniques in this article

6. Questions on Important Concepts

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

Refer the following example:

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

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

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

We use $.type(Object) which returns the built-in JavaScript type for the object.

68. What is Chaining in jQuery?

Chaining is a very powerful feature of jQuery. Chaining means specifying multiple functions and/or selectors to an element.

For example:

$(document).ready(function()
{
     $('#mydiv').css('color', 'blue');
     $('#mydiv').addClass('myclass');
     $('#mydiv').fadeIn('fast');
}

By using chaining we can write the above code as follows:

$(document).ready(function()
{
     $('#mydiv').css('color', 'blue').addClass('myclass').fadeIn('fast');
});

69. Which selectors are faster? ID or Class?

ID is absolutely the fastest. ID selectors are known to be faster than Class and Element selectors. Part of the reason is that ID is supposed to be unique, so the API stops searching after the ID is found in the DOM.

70. Is jQuery a W3C standard? Is it possible that jQuery HTML work for both HTML and XML?

No, jQuery is not a W3C standard. And no again, jQuery HTML only works for HTML document. It doesn’t work for XML documents.

7. General Questions

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

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

$(document).ready(function(){
    if ($('#element').length > 0){
       //Element exists
  }
});

72. Are events also copied when you clone any element in jQuery?

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

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

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.

74. How can we disable Browser’s Back button through jQuery?

We can do that like so:

$(document).ready(function() {
     window.history.forward(1);
     //OR
     window.history.forward(-1);
});

75. What is the difference between Map and Grep function in jQuery?

In $.map() you need to loop over each element in an array and modify its value whilst the $.Grep() method returns the filtered array using some filter condition from an existing array. The basic structure of Map() is: $.map ( array, callback(elementOfArray, indexInArray)).

76. How to disable jQuery animation?

Using jQuery property “jQuery.fx.off“, which when set to true, disables all the jQuery animation. When this is done, all animation methods will immediately set elements to their final state when called, rather than displaying an effect.

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

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

78. How does jQuery store data related to an element?

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

79. How we can use jQuery in ASP.NET?

Make a folder with the name Scripts inside your application. Right click on Scripts folder > Add Existing Item > Browse to the path where you downloaded the jQuery library (jquery-1.3.2.js) and the intellisense documentation (jquery-1.3.2-vsdoc2.js). Select the files and click Add. The structure will look similar to the following image:

jquery-qa-6
Folder and file organisation inside an .ASP project!

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

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.

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

This is a quite general question, but it will probably be part of any interview you experience:
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:

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

8. To conclude

If you are going for an interview, where role demands multiple skills e.g. Java, jQuery, it’s not expected from you to know every minor detail or comprehensive knowledge of jQuery, but if you are going for a purely client side development role, you might get tricky and advanced jQuery questions. Nevertheless, you can use these questions to quickly revise some of the most frequently asked jQuery questions on interviews and have a clearer idea on what’s coming.

Still with us? Wow, that was a huge article about different types of questions that can be used in a jQuery interview. If you enjoyed this, then subscribe to our newsletter to enjoy weekly updates and complimentary whitepapers!

So, what other jQuery interview questions are there? Let us know in the comments and we will include them in the article! Happy coding!

Fabio Cimo

Fabio is a passionate student in web tehnologies including front-end (HTML/CSS) and web design. He likes exploring as much as possible about the world wide web and how it can be more productive for us all. Currently he studies Computer Engineering, at the same time he works as a freelancer on both web programming and graphic design.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
kosidude
kosidude
8 years ago

Useful information but little old. Current version jquery is 1.12/2.2.
ajax success(), error() are deprecated as of jQuery 1.8
live() deprecated: 1.7, removed: 1.9

Andy
Andy
8 years ago

as a beginner to jquery this is very good info, thank you!!!

Sourav Basak
7 years ago

Thanks for sharing this article that distinguishes jQuery .bind() vs .live() vs .delegate() vs .on(). And it clears in depth view before applying to bind event to the elements.
Version comparison also supports when one method migrate to another one.

Here is another links for differentiate between .bind() vs .live() vs .delegate() vs .on().
http://www.namasteui.com/differences-between-jquery-bind-vs-live-vs-delegate-vs-on/

Hope this helps too. Thanks a lot.


Regards,
Sourav Basak [Blogger, Entrepreneur, Thinker]
Namaste UI

Peter
Peter
6 years ago

Wow that’s an extensive list of questions, and they’re all great. My only complaint would be that technical interviews also usually require coding, and solving problems, not just theoretical questions, so I recommend also practicing something like these jQuery interview questions: https://www.testdome.com/d/jquery-interview-questions/121

Back to top button