jQuery interview questions and answers - freshers, experienced

What is jQuery Selectors? Give some examples.

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

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

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

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

How can we give face effect in jQuery?

1. In jQuery we have three methods to give the fade effect to elements: fadeIn, fadeOut and fadeTo.
2. This methods change the opacity of element with animation.

Syntax:
$(selector).fadeIn(speed,callback)
$(selector).fadeOut(speed,callback)
$(selector).fadeTo(speed,opacity,callback)

1. “speed” can be one of following values : “slow”, “fast”, “normal” or milliseconds.
2. “opacity” specify the value that allows the fading to given opacity.
3. “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);
});

Explain the animate function.

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

Syntax:
$(selector).animate({params}, [duration], [easing], [callback])

1. “param” defines the CSS properties on which you want to apply the animation.
2. “duration” specify how long the animation will run. It can be one of following values : “slow”, “fast”, “normal” or milliseconds.
3. “easing” is the string which specify the function for the transition.
4. “callback” is the function which we want to run once the animation effect is complete.

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

Following is the jQuery to animate opacity, left offset, and height of the mydiv element
$('# clickToAnimate’).click(function()
{
     $('#book').animate({opacity: 0.30,left: '+=20',height: 'toggle'}, 3000, function()
{
     // run after the animation complete.
});
});

What is .siblings() method in jQuery?

1. When we want to fetch siblings of every elements in the set of matched elements then we can use siblings() method.
2. We filter the elements fetched by an optional selector.
3. Syntax : .siblings([selector])
4. “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’);

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

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

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

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

What is the use of jQuery.data()?

1. jQuery.data() is used to set/return arbitrary data to/from an element.
2. Syntax: jQuery.data(element, key, value)
3. “element” is the DOM element to which the data is associated.
4. “key” is an arbitrary name of the piece of data.
5. “value” is value of the specified key.
6. 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);

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

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

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

Above code will not work using live() method. But using delegate() method we can accomplish this.
$(document).ready(function()
{
$("#dvContainer")children("table").delegate("tr","click",function()
{
     alert($(this).text());
});
});

Explain the each() function.

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

Syntax :
$(selector).each(function (index, element))

1. “index” is the index position of the selector.
2. “selector” specifies the current selector where we can use “this” selector also.
3. 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.

Explain slideToggle() effect.

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

Syntax:
slideToggle([ duration] [, easing] [, callback])

1. “duration” is the number specifying how long the animation will run.
2. “easing” is the string which specify the function for the transition.
3. “callback” is the function which we want to run once the animation is complete.
4. 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.
5. We can specify the toggle speed with this effect.

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

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.

What is the use of param() method.

1. The param() method is used to represent an array or an object in serialize manner.
2. While making an ajax request we can use these serialize values in the query strings of URL.
3. Syntax: $.param(object | array, boolValue)
4. “object | array” specifies an array or an object to be serialized.
5. “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”

What is jQuery.holdReady() function?

- By using jQuery.holdReady() function we can hold or release the execution of jQuery’s ready event.
- This method should be call before we run ready event.
- To delay the ready event, we have to 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);
});

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

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

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

How to read, write and delete cookies in jQuery?

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

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

2. Read Cookie
$.dough("cookie_name");

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

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

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

What is Chaining in jQuery?

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

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

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

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

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

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

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

It will give following output:
Apple
Banana
Orange

Now we declare a numerical array and use sort() method to sort its elements.
$(document).ready(function()
{
     var mylist = [ “20”,”3””100”,”50”];
     mylist = mylist.sort();
     $(“#mydiv”).html(list.join(“”));
});

It will give following output:
100
20
3
50

What is difference between prop and attr?

1. In jQuery both prop() and attr() function is used to set/get the value of specified property of an element.
2. 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'

How to always reference latest version of jQuery?

When you reference the jQuery on your web page, you have to specify the version number also.
<script type=”text/javascript”
src=”http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js”>
</script>

Above code will always load the 1.5.1 version of jQuery. If you reference the latest jQuery then you don’t need to change the code every time the new version of jQuery is released.

To achieve this you have to use following code
<script type=”text/javascript”
src=”http://code.jquery.com/jquery-latest.min.js”>
</script>

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

What is resize() function in jQuery?

The resize() function is called whenever the browser size is changed. This event can be only used with $(window).

Syntax:
.resize([event_data], handler(event_object))

- The “event_data” is the data to be sent to the handler.
- The “handler(event_object)” is a function to be called each time when the window is resized.

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

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

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>

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

- 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 <p> elements.
$("p.intro") will select all <p> elements with class="intro" defined in them.
$("p#demo") this will select all <p> 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".

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

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

1. $(selector).slideDown(speed,callback)
2. $(selector).slideUp(speed,callback)
3. $(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.

What are the various ajax functions?

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:

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

3. Shorthand ajax methods : They comprise of simply the wrapper function that call $.ajax() with certain parameters already set.
4. $.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.

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

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.

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

There are two ways to handle this issue:

1. 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 <a> element:
$('#mydiv').click(function(e)
{
     if( $(e.target).is('a') )
     fn.call(e.target,e);
});
$('#mydiv').load('my.html')

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

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

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.

Why is the block display style used for animations?

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.

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

There are two approaches of doing so:

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

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

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

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

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.

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

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

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

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.

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

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

Some of the key concepts that should be followed while:

1. 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.
2. Use inheritance techniques to avoid rewriting a code again and again.
3. The jquery is dom centric in nature but not all applications are such in nature. All funtionalities should not have a dom representation.
5. 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.

How can related code be encapsulated? Give example.

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

Write a code for the implementation of a module pattern.

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

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

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

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

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

1. $.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.
2. $.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' ]);

What is the Struts2 jQuery plugin and its advantages.

The struts2 jquery plugin is used to:
1. It provides the user with an easy integration of ajax and widgets.
2. 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:
1. It reduces the number of code to be written dramatically.
2. It also supports ajax form validation.
3. The code becomes much easier to read and hence prevents errors from occurring and is easy to debug.
What is jQuery?
What is jQuery? - jQuery is a JavaScript library that simplifies JavaScript and AJAX programming
Advantages of jQuery
The advantages of using jQuery are....
Features of jQuery
Features of jQuery - Effects and animations, Extensibility, DOM element selections functions, CSS manipulation..........
Post your comment