FREE Web Template Download
HTML CSS JAVASCRIPT SQL PHP BOOTSTRAP JQUERY ANGULARJS TUTORIALS REFERENCES EXAMPLES Blog
 

Top JQuery Interview Questions and Answers



Top 50 JQuery Interview Questions & Answers

1. What is jQuery?

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

2. Why jQuery is needed?

jQuery is needed for the following list:

  • Used to develop browser compatible web applications
  • Improve the performance of an application
  • Very fast and extensible
  • UI related functions are written in minimal lines of codes

3. Whether jQuery HTML work for both HTML and XML documents?

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

4. What are the methods used to provide effects?

Some of the effects methods are:

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

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

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

JQuery Interview Questions and Answers

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

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

7. Which operating system is more compatible with jQuery?

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

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

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

9. Which command will give a version of jQuery?

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

10. In what scenarios jQuery can be used?

jQuery can be used in following scenarios:

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

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

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

12. What is jQuery connect?

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

13. How to use connect?

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

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

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

15. What are the browser related issues for jQuery?

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

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

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

17. What are the basic selectors in jQuery?

Following are the basic selectors in jQuery:

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

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

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

19. What is the use jQuery.data method?

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

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

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

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

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

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

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

23. What is the use of jQuery load method?

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

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

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

var sample = $.noConflict()

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

The four parameters are

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

26. What is the use of jQuery filter?

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

27. Which program is useful for testing jQuery?

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

28. What is CDN?

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

29. What are the two types of CDNs?

There are two types of CDNs:

  • Microsoft – Load jQuery from Ajax CDN
  • Google – Load jQuery from Google libraries API

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

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

31. Is jQuery is a client or server scripting?

jQuery is a client scripting.

32. What is the script build up by jQuery?

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

33. How can we debug jQuery?

There are two ways to debug jQuery:

Debugger keyword

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

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

Following are the ways to include jQuery in a page:

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

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

jQuery.ajax method is used for asynchronous HTTP requests.

36. Where can we download JQuery?

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

37. Is jQuery is a replacement of JavaScript?

No, jQuery is not a replacement of JavaScript.

38. What is called chaining?

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

39. What are the advantages of jQuery?

Following are the advantages of jQuery:

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

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

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

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

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

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

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

43. What is the use of jQuery each function?

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

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

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

45. Which is the fastest selector in jQuery?

ID and Element are the fastest selectors in jQuery.

46. What is the slowest selector in jQuery?

Class selectors are the slowest selectors in jQuery.

47. Where jQuery code is getting executed?

jQuery code is getting executed on a client browser.

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

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

49. Why jQuery is better than JavaScript?

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

50. What are the types of selectors in jQuery?

There are three types of selectors in jQuery:

  • CSS Selector
  • XPath Selector
  • Custom Selector

jQuery Interview Question

A list of top frequently asked jQuery interview questions and answers are given below.


1) What is jQuery?

jQuery is a fast, lightweight, feature-rich client side JavaScript framework. It has provided a much needed boost to JavaScript. Before jQuery, JavaScript codes were lengthy and bigger, even for smaller functionality.


2) Is jQuery a programming language?

jQuery is not a programming language but a well written JavaScript code. It is used to traverse documents, event handling, Ajax interaction and Animation.


3) What is the difference between JavaScript and jQuery?

The simple difference is that JavaScript is a language while jQuery is a built-in library built of JavaScript. jQuery simplifies the use of JavaScript language.


4) Is jQuery replacement of JavaScript?

No, jQuery is not the replacement of JavaScript. jQuery is written on the top of JavaScript and it is a different library. jQuery is lightweight JavaScript library which is used to interact JavaScript and HTML.


5) Why do we use jQuery?

  • It is very easy to learn and use.
  • It is used to develop browser compatible web applications.
  • It improves the performance of an application.
  • It is very fast and extensible.
  • It facilitates you to write minimal lines of codes for UI related functions.
  • It provides a cross-browser support.

6) What are the effects methods used in jQuery?

These are some effects methods used in jQuery:

  • show()
  • hide()
  • toggle()
  • fadeIn()
  • fadeOut()

7) Is it possible that jQuery HTML work for both HTML and XML document?

No, jQuery HTML only works for HTML document. It doesn't work for XML documents.


8) What is $() in jQuery library?

The $() function is an alias of jQuery() function. It is used to wrap any object into jQuery object which later facilitates you to call various method defined jQuery object. You can pass a selector string to $() function and it will return jQuery object which contains an array of all matched DOM elements.


9) Is jQuery library used for server scripting or client scripting?

It is a library for client side Scripting.


10) Is jQuery a W3C standard?

No, jQuery is not a W3C standard.


11) What is the starting point of code execution in jQuery?

$(document).ready() function is the starting point of jQuery code. It is executed when DOM is loaded.


12) What is the basic requirement to start with the jQuery?

You need to make reference of its library to start with jQuery. You can download the latest version of jQuery from jQuery.com.


13) Can you use a special character in place of $ (dollar sign) in jQuery?

Yes.


14) Can you use multiple document.ready() function on the same page?

Yes. You can use any number of document.ready() function on the same page.


15) What is the difference between find and children methods?

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


16) What is a CDN?

CDN stands for Content Delivery Network or Content Distribution Network. It is a large distributed systems of servers deployed in multiple data centers across the internet.


17) What is the goal of CDN and what are the advantages of using CDN?

The main goal of the CDN is to provide content to the end-users with high availability and high performance.

Advantages of using CDN:

  • It reduces the load from the server.
  • It saves bandwidth. jQuery framework is loaded faster from these CDN.
  • If a user visits regularly a site which is using jQuery framework from any of these CDN, it will be cached.

18) How can you use jQuery library in your project?

You can use jQuery library in ASP.Net project from downloading the latest jQuery library from jQuery.com and include the references to the jQuery library file in your HTML/PHP/JSP/Aspx page.

  1. <script src="_scripts/jQuery-1.2.6.js" type="text/javascript"></script>   
  2. <script language="javascript">   
  3. $(document).ready(function() {   
  4. alert('test');   
  5. });   
  6. </script>  

19) What are selectors in jQuery? How many types of selectors in jQuery?

If you want to work with an element on the web page, first you need to find it. Selectors are used to find the HTML elements in jQuery. There are many types of selectors. Some basic selectors are:

  • Name: It is used to selects all elements which match with the given element Name.
  • #ID: It is used to selects a single element which matches with the given ID
  • .Class: It is used to selects all elements which match with the given Class.
  • Universal (*): It is used to selects all elements available in a DOM.
  • Multiple Elements E, F, G: It is used to selects the combined results of all the specified selectors E, F or G.
  • Attribute Selector: It is used to select elements based on its attribute value.

20) What is use of jQuery filter?

: jQuery filter is used to filter the certain values from the object. It filters the result of your original query into specific elements.


21) What are the different types of selectors in jQuery?

There are three types of selectors in jQuery:

  • CSS Selector
  • Custom Selector
  • XPath Selector

22) What is the difference between ID selector and class selector in jQuery?

ID selector and class selector are same like they are used in CSS. ID selector uses ID while class selector uses class to select elements.

If you need to select just one element, use ID selector. If you want to select a group of elements, having same CSS class, use class selector.


23) How to add and remove CSS classes to an element using jQuery?

You can use addclass() jQuery method to add CSS class to an element and removeclass() jQuery method to remove CSS class from an element.


24) Can you write a jQuery code to select all links inside the paragraph?

Yes. You can use <a> tag nested inside paragraph <p> tag to select all links.


25) What is the difference between prop and attr?

attr(): It gets the value of an attribute for the first element in the set of matched element.

prop(): it gets the value of a property for the first element in the set of matched elements. It is introduced in jQuery 1.6.


26) What are the two types of CDNs?

There are two types of CDN:

  • Microsoft: It loads jQuery from AJAX CDN.
  • Google: It loads jQuery from Google libraries API.

27) What is the use of animate function in jQuery?

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

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

Here,

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

28) How can you disable jQuery animation?

By using jQuery property "jQuery.fx.off" and setting it to true, you can disable jQuery animation.

 

 

 

 

 

 

 

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.