Wednesday, 7 December 2011

Basic JQuery Interview Questions


What is jQuery & its significance? Why it is so popular?
jQuery is lightweight, client side script JavaScript library file that supports all browsers.Query is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery makes it easy to play with the DOM, add effects, and execute Ajax requests.
This helps developer to reduce lines of code while he program. For example huge code written in Java Script, can be done easily with JQuery in one or two lines as it uses pre compiled JavaScript library internally. For example To find a Div that have class xxx we can do this using custom JavaScript by looping through all DOM elements, Find Div element write if statement checking the class then write the code to manipulate cross browser.  But this can be achieved using jQuery with 2 lines of code. jQuery is a fun library to use and play.
It is so popular due to the below 10 reasons.
  • Cross Browser Compatibility.
  • Fast but micro Famework.The jQuery core library minified is only about 24KB in size, so it is very easily to include in any application and it is pretty fast as well.
  • Easy to learn and flexible.
  • It is well documented.
  • Reuse of plug-ins across projects .These plug ins are extendable.
  • Latest CSS Complaint.
  • Microsoft, which now includes jQuery with its MVC framework and integrated to VS2010 with intellisense support .
  • IBM, Netflix use jQuery. Nokia have adopted it. Google uses and hosts the jQuery library.
  • Easy to find support since there is a large development community and variety of plug-ins.
  • DOM manipulation with querying and chaining is Wonderful & Robust. It is simple, concise and clear enough.
Hence jQuery is definitely faster, easier and more productive than previous traditional JavaScript that we use, hence its so popular.
Now the Client side development is fun using jQuery Agree or not ??
What are jQuery Class Selectors and ID selectors Explain them?
jQuery selectors  allows to easily identify set of page elements for performing user friendly or required operations .
In general, Selection of elements  can be 3 types in jQuery. They are
1.  Class Selector (.)
2.  ID Selector (#)
3.  Element selector (<element tag>)
We will learn Class and ID selectors in this article and will learn about element selectors in the next article.
Class Selector (.)
A class selector is to identify class to search for. An element can have multiple classes. There is no restriction.  Operations are applied based on the class that matches.
$(.demo) – Selects all elements in side a web page with the class demo
Example of using class Selector
01.<html>
02.<head>
03.<script src="http://code.jquery.com/jquery-latest.js"></script>
04.</head>
05. 
06.<body>
07.<div class="beyondrelational"> This is Div  using class selector </div>
08.<p class="beyondrelational"> This is P using class selector </p>
09. 
10.<script>$(".beyondrelational").css("border","8px solid blue");</script> 
11.</body>
12. 
13.</html>
ID Selector (#)
An element can be selected or indentified based on id.  It Matches a single element with the given id attribute.
$('#EmpNo)  - Selects an element with the ID EmpNo in the web page.
Example of using ID Selector
01.<html>
02.<head>
03.<script src="http://code.jquery.com/jquery-latest.js"></script>
04.</head>
05. 
06.<body>
07.<div id="beyondrelational"> This is Div class using ID selector </div>  
08.<script>$("#beyondrelational").css("border","8px solid blue");</script> 
09.</body>
10.</html>
Selecting class and ID Selectors at a time (Multiple selectors)
1.$("#IDSel, .ClassSel")
The above selector syntax selects all elements with id IDSel and the class ClassSel.
We can also select elements in webform directly using jQuery , that we will discuss in next post. Till then keep visiting !!!
What is the significance of jQuery.NoConflict?
If we are referring any other script files along with jQuery you may get conflicts in the namespace. Some times if we use jQuery with any other libraries, we may get clash between two libraries and we encounter situations like neither of the functionality works.
Important thing to keep in mind is , when we call .noConflict() jQuery will return $() to it’s previous owner .So we  need to use jQuery() instead of  $() function.
The following example illustrated how to use no conflict . This can be used in cases “where one script works with out the other and will not work when both the scripts are combined”.
01.<html>
02.<head>
03.<script src="xxx.js"></script>
04.<script src="jquery.js"></script>
05.<script>
06.jQuery.noConflict();
07. 
08.// Use jQuery via jQuery(...)
09.jQuery(document).ready(function(){
10.jQuery("div").hide();
11.});
12. 
13.//can Use Prototype with $(...), etc.
14.$('id').hide();
15.</script>
16.</head>
17.<body></body>
18.</html>
The jQuery library and all  plugins are within the jQuery namespace. But "global" objects are stored inside the jQuery namespace . so It is usual to get namespace clash  between jQuery and any other library or plug-in. $ is just short cut for jQuery. Hence overriding $ function will work.
You can also assign in another variable and use it in the application like this as shown below.
01.<html>
02.<head>
03.<script src="xxx.js"></script>
04.<script src="jquery.js"></script>
05.<script>
06.var $j = jQuery.noConflict();
07. 
08.// Use jQuery via $j(...)
09.$j(document).ready(function(){
10.$j("div").hide();
11.});
12. 
13.// Use Prototype with $(...), etc.
14.$('someid').hide();
15.</script>
16.</head>
17.<body></body>
18.</html>
Working with jQuery Selectors – Events .
How to get All I tags inside an element with id ‘header’ ?
Now  we understood what is ID selector, class selector and to select elements, putting all together we will try to answer the above question
For ex: $('#header >I')  - Gets get All I tags inside an element with id ‘header’ .

ID Selector with on Click Event
1.$('#header >I') .Click(function()
2.{   //Open
3.alert(this.innerHTML);
4.});  // Close
Here we are firing click event means that, the mouse click event fires the function. And the corresponding operations in the event are fired. In this case a simple alert message.
 Class Selector with Mouse Over Event
1.$('.content').mouseover(function()
2.{
3.this.innerHTML = 'Content Replaced';
4.});
The above code snippet select all the elements that has class ‘content’,Mouse over of the element content/ text associated with element will be replace
Here Methods can be applied to sequence of objects.
How can you select various HTML Elements using jQuery?
jQuery can be used to select HTML elements using element selector. Below are some of the examples of how to use selectors.
  • $(<’element>’)  - Selects all elements with the given tag name.
  • $(‘p’) – Selects all  Paragraph  Elements
  • $(‘a’) – Selects all Anchor tags in side a web page
  • $(‘I’)  - Selects all Italic tags in the webpage
  • $(‘input[type=text]’) – Selects all textboxes in side a webpage
After selection we can call methods .
Selecting multiple elements
$(‘p,a,div,span’) – Selects all p, a, div, span elements in the web page.
<script>$("p").after( $("b") );</script>
The above script selects all p and makes the content after <p> tag as bold. 
Selecting all the elements
$(‘*’) – This will select all html elements in web form 
Example
<html>
<head><script src="http://code.jquery.com/jquery-latest.js"></script> </head>
<body>
<input type='text' />
<textarea > </textarea>
</body>
<script>
$('input[type=text], textarea').css({width: '70%'});
</script>
</html>
What are jQuery Class Selectors and ID selectors Explain them?
jQuery selectors  allows to easily identify set of page elements for performing user friendly or required operations .
In general, Selection of elements  can be 3 types in jQuery. They are
1.  Class Selector (.)
2.  ID Selector (#)
3.  Element selector (<element tag>)
We will learn Class and ID selectors in this article and will learn about element selectors in the next article.
Class Selector (.)
A class selector is to identify class to search for. An element can have multiple classes. There is no restriction.  Operations are applied based on the class that matches.
$(.demo) – Selects all elements in side a web page with the class demo
Example of using class Selector
01.<html>
02.<head>
03.<script src="http://code.jquery.com/jquery-latest.js"></script>
04.</head>
05. 
06.<body>
07.<div class="beyondrelational"> This is Div  using class selector </div>
08.<p class="beyondrelational"> This is P using class selector </p>
09. 
10.<script>$(".beyondrelational").css("border","8px solid blue");</script> 
11.</body>
12. 
13.</html>
ID Selector (#)
An element can be selected or indentified based on id.  It Matches a single element with the given id attribute.
$('#EmpNo)  - Selects an element with the ID EmpNo in the web page.
Example of using ID Selector
01.<html>
02.<head>
03.<script src="http://code.jquery.com/jquery-latest.js"></script>
04.</head>
05. 
06.<body>
07.<div id="beyondrelational"> This is Div class using ID selector </div>  
08.<script>$("#beyondrelational").css("border","8px solid blue");</script> 
09.</body>
10.</html>
Selecting class and ID Selectors at a time (Multiple selectors)
1.$("#IDSel, .ClassSel")
The above selector syntax selects all elements with id IDSel and the class ClassSel.
We can also select elements in webform directly using jQuery , that we will discuss in next post. Till then keep visiting !!!
What are jQuery Selectors? Explain them?
A Selector identifies an HTML element tag that is used to manipulate with jQuery code.
Selectors allow page elements to be selected. $ is the symbol used for it.
$ can also be called as jQuery selector. Selectors are the most important part of the jQuery , we can say that heart of jQuery.
  • We can select single (using id selectors) or multiple elements using class or element selectors
  • Selectors find DOM Elements to manipulate based on CSS Selector syntax
    Selectors can find the elements by ID, class, Element Name and hierarchical positioning .
  • Selectors can return sequence of DOM elements , and we can use methods or logic on every matched element.
Selectors syntax can be in either of  following 2 ways :
$(Selector Expression)
or
jQuery(Selector Expression)
jQuery has different types of selectors
1. Class Selectors
2. ID Selectors
3. Element Selectors
What is difference between jQuery and Microsoft Ajax? When do you use Ajax and When do you use jQuery? What is the significance of each?
jQuery is like the ASP.NET AJAX Client Framework (MicrosoftAjax.js), with selectors, DOM selections/ manipulations, plug-ins, and better animation support.  jQuery is more powerful than MS AJAX on the client side due to its light weight nature .  This is the reason Microsoft integrated jQuery with Visual Studio. JQuery is integrated for post  VS versions 2008, no explicit download of jQuery file is required for the versions above VS2010.  
Ajax is a Technology for Asynchronous Data Transferring. AJAX is a technique to do an XMLHttpRequest  from a web page to the server and send or receive data to be used on the web page.
jQuery can be used
If you love and comfortable with JavaScript
Most interaction is client-side only
If a custom solution is required
For stunning look and feel of client side UI
If animations ,DOM Selection are required
Ajax can be used
If you are using ASP.NET & VS
When server side Integration is required.
If you need json and WCF Support
Conclusion
  • jQuery and Ajax often used in conjunction with each other for better results.
  • jQuery is  used to modify data on the webpage dynamically and it  can use AJAX to retrieve data that needs without changing the current state of the displayed page through partial post backs
·         Playing with CSS in jQuery – How to work with CSS in jQuery?
·         How can we apply css to elements using JQuery library.
·         The below example is to apply css on div element that has id as DivId.
·         1.$(”#DivId “).css(”border”,”4px  red”);
·         To apply css in odd childs of parent node using JQuery library.
·         1.$(”tr:odd”).css(”background-color”, “#bbbbff”);
·         To apply css in even childs of parent node using JQuery library.
·         1.$(”tr:even”).css(”background-color”, “#bbbbff”);
·         To apply css in last child of parent using JQuery library.
·         1.$(”tr:last”).css({backgroundColor: ‘yellow’, fontWeight: ‘bolder’});
·         Now How can we modify css class using JQuery library?
·         Suppose that Css class has following definition
·         1..class
·         2.{
·         3.font-size:10px;
·         4.font-weight:normal;
·         5.color:#000000;
·         6.}
·         Now  if we are intrested to  add border property on above class, so we should follow below code.
·         1.$(“.class”).css(“border”,”1px solid blue”);
·         Where $(“.class”) name of css class. Now .class will automatically add border property in his class definition.
Happy jQuerying !!!!
What is $.disconnect significance and how it is different from $.disconnectAll
In jQuery to disconnect one function from another function then $.disconnect is used. Once this statement gets executed, function gets disconnected from reference function and the connected function will not be executed after the code.
Syntax is same as connect function. To disconnect c2.fun1 use the following code
1.$.disconnect(a,'fun1',b,fun2);
Where fun1 is the reference function and fun2 is connected function. Here a, b are objects.
$.disconnectAll function is used to disconnect all connected functions.
1.$.disconnectAll(a,'fun1');

What is jQuery Connect ? How to use jQuery Connect?
This is a jQuery plugin that is used to connect / bind a function to another function. It is more of assigning a handler for another function. Connect is used to execute a function whenever a function from another object or plugin is executed. We can connect to an event of a DOM element too using this function. In the sense same connect function can be used for both DOM elements and for the functions.
1.$.connect(refobj,refFuncName, connObj,connFunc);
This means that, when the reference function is executed, the connected function gets executed automatically after it. To understand more please analyze the following example
01.function A(){
02.this.fun1 = function(){
03.called1 = 'calssA-fun1';
04.}
05.}
06.var a = new A();
07.function B(){
08.this.fun2 = function(){
09.called2 = 'classB-fun1';
10.}
11.}
12.var b = new B();
13.$.connect(a,'fun1',b,fun2);
Here we connected "fun2" of object b to "fun1" of object a. When we call b.fun2, a.fun1 will also execute automatically.
This is very handy to execute some function when some other function is executed from the plug-in . In order to play with it follow these steps.
  • Download jquery.connect.js file.
  • Include this file in your html file.
  • Take help of $.connect function as illustrated to connect a function to another function.
In what scenarios jQuery can be used?
  • To apply CSS static or dynamic
  • To call functions on events
  • Crisscross the documents
  • Manipulation purpose
  • To add animation effects
In all the cases we are using JavaScript can be replaced with jQuery in the projects. This can reduce maintenance.

Do you prefer jQuery or JavaScript? Explain Why?
jQuery solves major JavaScript problems.
jQuery is preferred over JavaScript due to following reasons.
jQuery is light weight library for developing client side applications including ajax.
jQuery assists to keep code simple and concise and reusable. Huge line of code developed using JavaScript can be eliminated with just few lines of jQuery.
jQuery library simplifies the process of traversal of HTML DOM tree.
jQuery can also handle events, perform animation, and add Ajax support in web applications.
Creating animation and effects using JavaScript is not an easy task and requires deep understanding and imagination. This is quite difficult to do using JavaScript.
When a client wants  to zoom entire screen, or to show a slideshow of photographs, this can be achieved using jQuery.  With a few script includes and smart work , its  possible and extremely effective.  Using  variety of jquery Plugging that are available customization is easy for developers , web developers have control over the effects without even touching a single line of raw Javascript.  Thats the power of query.
If you know the JavaScript well, it helps you to make better use of jQuery.
To distinguish jQuery from JavaScript Here is an example for basic animation using javascript .
01.var example = null; // object
02.function doMove() {
03.example.style.left = parseInt(example.style.left)+1+'px';
04.setTimeout(doMove,20); // call doMove in 20msec
05.}
06.function init() {
07.example = document.getElementById('example'); // get the "example" object
08.example.style.left = '0px'; // set its initial position to 0px
09.doMove(); // start animating
10.}
11.window.onload = init;
Now if we we wanted to customize the animation or add wavy or some other different animation its quite difficult using JavaScript. But using jQuey its easy to customize using Plug-ins available. The same animation can be achieved using jQuery as
1.$("#element").animate({ left: 200px; });
JavaScirpt is a Sea and jQuery is a Ship . Together allow us to sail if used effectively. We should only know when to use what!!!

What are the advantages of jQuery?
  1. Easy and Self Explanatory
  2. JavaScript enhancement without headache of learning new syntax.
  3. The code is simple, clear, readable, reusable and also easy to maintainable.
  4. Elimination of writing repeated, complex loops and DOM scripting library calls.
Explain how jQuery works?
The $() function is an alias for the jQuery() function . This returns a special Java-Script object. This JavaScript Object contains an array of  DOM elements that matches the selector. Selector is key thing in jQuery development.It is away to select node from DOM. This Java-Script object possesses a large number of useful predefined methods that can action group of elements.This type of construct is termed a wrapper because it wraps the matching element(s) with extended functionality.
  • Here $(object) is called jQuery wrapper around the object.
  • jQuery has a ready element that checks the document and waits until document is ready to be manipulated.
  • It searches for the reference files for framework, once it finds it then control goes to the function specified.
  • What ever code mentioned in the function that gets executed. Event handling also can be implemented here.
Consider the following example.
01.<html>
02.<head>
03.<script type="text/javascript" src="jquery.js"></script>
04.<script type="text/javascript">
05.$(document).ready(function(){
06.// Your code here
07.alert(“Checking function Fired”);
08. 
09.}
10.) ;
11.</script>
12.</head>
13.<body>
14.<a href="http://www.beyondrelational.com /">Beyond Relational jQuery FAQ </a>
15.</body>
16.</html>
1.<strong><em>Note :We can also use jQuery(document) instead of $. </em></strong>
  • You can debug the jquery script by placing debugger keyword (OR) attaching worker process and then inserting a break point .
How did you use jQuery in ASP.Net Application? Explain with an example?
·         Download the latest jQuery library from jQuery.com http://docs.jquery.com/Downloading_jQuery.
·         Add reference to the jQuery library file in ASPX page / Master page that uses jQuery.
·         1.<script src="_scripts/jQuery-1.5.js" type="text/javascript"></script>
·         2.<script language="javascript">
·         3.$(document).ready(function(){ $("a").click(function(event)
·         4.{ alert("Welcome to jQuery"); }); });
·         5.</script>

Does document.ready() function similar to onload()? (or) Explain the importance of document.ready()? (or) Why jQuery script is faster?
Document.ready() function is completely different from body onload() function .
Explanation
JavaScript Operations on the page elements are performed outside of the DOcument Markup (DOM) that creates them. This is because of waiting until  DOM elements of the page are fully loaded before those operations execute. The onload handler for the window object is used for this purpose, executing statements after the entire page is fully loaded.
Browser delays calling onload till DOM tree is created and then  all images/other external resources are fully loaded.
jQuery waits until DOM tree is ready before executing scripts. jQuery uses this approach using Document.Ready . This makes running scripts fast. jQuery triggers execution of code once the DOM tree is loaded , but not external image resources has loaded.  Hence script execution need not wait till the page is loaded. The code execution happens before page is loaded hence jQuery code is faster. We can use this technique multiple times within the same HTML document.
To summarize the differences
  • First of all Document.ready() function is called as soon as DOM is loaded but body.onload() function is called when everything gets loaded on the page that includes DOM, images and all associated resources of the page.
  • We can have as many document.ready() functions in a page but onload function is limited on one time.
What do Dollar ($) sign significance in jQuery?
Dollar Sign is nonetheless an alias for JQuery. You can write jQuery syntax using $ sign or jQuery.
This can also be called Selector($).
This can be called as an expression for identifying target elements on a page that allows  to easily identify and also  grab elements required.
The below 2 syntaxes are the same to create a function using jQuery.
To collect a group of elements, we use the simple syntax $(selector) or jQuery(selector).
1.$(document).ready(function()
2.{
3. 
4.});
OR
1.jQuery(document).ready(function()
2.{
3. 
4.});
Example for a Hyperlink Click
1.$("a").click(function() {});

What are the various jQuery features?

The following are important features of jQuery.
Extensibility
The jQuery Framework is easily extensible. 
DOM elements manipulations
It easily handles DOM element selections functions, manipulations, traversal and modification.
Event Handling
We can implement Event Handling at client side.
CSS manipulation
It provides the flexibility for CSS manipulation. We can apply or change CSS dynamically using jQuery.
Animations
Advanced effects and animations are possible using jQuery.
Cross Browser Compatibility
It is Consistent across all browsers.
Easy Plugins
Number of plug-in or widgets available to achieve certain functionality like paging, sorting, drag , accordion etc.
What is jQuery UI?
jQuery UI  is a library which is built on top of JQuery library.  It can be called as one of the JavaScript plug-in that allows to create animations, sortables list, draggle list . This is developed as separate JavaScript File. This can be downloaded from http://ui.jquery.com/download (ui.jQuery.js).
jQuery UI  responsible for widgets,  components , themes , advanced effects , animation  and interaction mechanism that is UI related things.
Accordions, sliders, dialog boxes, date pickers, and more. All these are ready to be used right now.
jQuery UI  can be used to build highly interactive web applications.
You need to include latest jQuery , UI Core and Flora theme style sheet to work with jQuery UI.
In addition to the above source files you may need to refer each of the component files like ui.draggable.js, ui.resizable.js, ui.accordian.js etc .
or  you may will have to refer jquery.ui.all.js script that contains all component .js files . But do not refer all if you are not using . It is advised to refer only the required files. You can also build the custom download .js file by selecting the required widgets .
This is used for Resizing (resizable method is plugged in jQuery UI), Exploding or animations.
The following is an example code that uses  jQuery UI.
Refer the script files.
1.<link rel="stylesheet" href="themes/flora/flora.all.css" type="text/css" media="screen" title="Flora (Default)" />
2.<script src="http://code.jquery.com/jquery-latest.js"></script>
3.<script src="ui/ui.core.js"></script>
Refer the required Components
1.<script src="ui/ui.draggable.js"></script>
2.<script src="ui/ui.resizable.js"></script>
3.<script src="ui/ui.accordion.js"></script>
1.$(document).ready(function() {
2.$("#dragme").draggable();
3.$("#dragme-x").draggable({ axis: "x" });
4.$("#accordionDemo").accordion({ event: "mouseover" });
5.$("#dragme-resize").draggable().resizable();
6.})
jQuery UI future is hope to be expecting excited and positive.


Original source and author = Hema
http://beyondrelational.com/blogs/hima/archive/2011/10/01/basic-jquery-interview-questions.aspx

Post a Comment