Thursday, February 21, 2013

jquery interview questions and answers

1) What is jQuery Selectors? Give some examples.

  • jQuery Selectors are used to select one or a group of HTML elements from your web page.
  • jQuery support all the CSS selectors as well as many additional custom selectors.
  • jQuery selectors always start with dollar sign and parentheses: $()
  • There are three building blocks to select the elements in a web document.
1) Select elements by tag name
Example: $(div)
It will select all the div elements in the document.
2) Select elements by ID
Example: $(#xyzid”)
It will select single element that has an ID of xyzid
3) Select elements by class
Example: $(“.xyzclass”)
It will select all the elements having class xyzclass

2) How can we give face effect in jQuery?

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

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

3) Explain the animate function.

-The animate function is used to apply the custom animation effect to elements.
-Syntax:
$(selector).animate({params}, [duration], [easing], [callback])
  • “param” defines the CSS properties on which you want to apply the animation.
  • “duration” specify how long the animation will run. It can be one of following values : “slow”, “fast”, “normal” or milliseconds
  • “easing” is the string which specify the function for the transition.
  • “callback” is the function which we want to run once the animation effect is complete.
For example
<div id="clickToAnimate">
Click Me
</div>
<div id="mydiv" style=”width:200px; height:300px; position: relative; right: 20px;">
</div>

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

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

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

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

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

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

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

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

8) Explain the each() function.

-The each() function specify the function to be called for every matched element.
Syntax:
$(selector).each(function (index, element))
  • “index” is the index position of the selector.
  • “selector” specifies the current selector where we can use “this” selector also.
  • In the case when we need to stop the each loop early then we can use “return false;”
For example
$("#clickme").click(function(){
$("li").each(function(){
document.write($(this).text())
});
});
This will write the text for each “li” element.

9) Explain slideToggle() effect.

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

Syntax:
slideToggle([ duration] [, easing] [, callback])
  • “duration” is the number specifying how long the animation will run.
  • “easing” is the string which specify the function for the transition.
  • “callback” is the function which we want to run once the animation is complete.
  • If the element is visible then this effect will slide the element up side and make it completely hidden. If the element is hidden then slideToggle() effect will slide it down side and make it visible.
  • We can specify the toggle speed with this effect.
For example
$("#clickme").click(function(){
$("#mydiv").slideToggle(“slow”, function(){
//run after the animation is complete.
});
});

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

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

  • The param() method is used to represent an array or an object in serialize manner.
  • While making an ajax request we can use these serialize values in the query strings of URL.
  • Syntax: $.param(object | array, boolValue)
  • “object | array” specifies an array or an object to be serialized.
  • “boolValue” specifies whether to use the traditional style of param serialization or not.
For example:
personObj=new Object();
empObject.name="Arpit";
empObject.age="24";
empObject.dept=”IT”;
$("#clickme").click(function(){
$("span").text($.param(empObject));
});
It will set the text of span to “name=Arpit&age=24&dep=IT”

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

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

14) How to read, write and delete cookies in jQuery?

-To deal with cookies in jQuery we have to use the Dough cookie plugin.
-Dough is easy to use and having powerful features.
-Create cookie
$.dough("cookie_name", "cookie_value");
Read Cookie
$.dough("cookie_name");
Delete cookie
$.dough("cookie_name", "remove");

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

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

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

18) What is difference between prop and attr?

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

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

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

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

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

No comments:

Post a Comment