Friday, October 10, 2014

jQuery IQ's

jQuery IQ's


Q1. What is jQuery?

Ans: jQuery is fast, lightweight and feature-rich client side JavaScript Library/Framework which helps in to traverse HTML DOM, make animations, add Ajax interaction, manipulate the page content, change the style and provide cool UI effect. It is one of the most popular client side library and as per a survey it runs on every second website.

Q2. Why do we use jQuery?

Ans: Due to following advantages.
Easy to use and learn.
Easily expandable.
Cross-browser support (IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+)
Easy to use for DOM manipulation and traversal.
Large pool of built in methods.
AJAX Capabilities.
Methods for changing or applying CSS, creating animations.
Event detection and handling.
Tons of plug-ins for all kind of needs.

Q3. How JavaScript and jQuery are different?

Ans: JavaScript is a language While jQuery is a library built in the JavaScript language that helps to use the JavaScript language.

Q4. Is jQuery replacement of Java Script?

Ans: No. jQuery is not a replacement of JavaScript. jQuery is a different library which is written on top of JavaScript. jQuery is a lightweight JavaScript library that emphasizes interaction between JavaScript and HTML.

Q5. Is jQuery a library for client scripting or server scripting?

Ans. Client side scripting.

Q6. Is jQuery a W3C standard?

Ans: No. jQuery is not a W3C standard.

Q7. What is the basic need to start with jQuery?

Ans: To start with jQuery, one need to make reference of it's library. The latest version of jQuery can be downloaded from jQuery.com.

Q8. Which is the starting point of code execution in jQuery?

Ans: The starting point of jQuery code execution is $(document).ready() function which is executed when DOM is loaded.

Q9. What does dollar sign ($) means in jQuery?

Ans: Dollar Sign is nothing but it's an alias for JQuery. Take a look at below jQuery code.
 Collapse | Copy Code
$(document).ready(function(){
});
Over here $ sign can be replaced with "jQuery" keyword.
 Collapse | Copy Code
jQuery(document).ready(function(){
});
Q10. Can we have multiple document.ready() function on the same page?

Ans: YES. We can have any number of document.ready() function on the same page.

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

Ans: Yes. It is possible using jQuery.noConflict().

Q12. Is it possible to use other client side libraries like MooTools, Prototype along with jQuery?

Ans: Yes.

Q13. What is jQuery.noConflict?

Ans: As other client side libraries like MooTools, Prototype can be used with jQuery and they also use $() as their global function and to define variables. This situation creates conflict as $() is used by jQuery and other library as their global function. To overcome from such situations, jQuery has introduced jQuery.noConflict().
 Collapse | Copy Code
jQuery.noConflict();
// Use jQuery via jQuery(...)
jQuery(document).ready(function(){
   jQuery("div").hide();
});
You can also use your own specific character in the place of $ sign in jQuery.
 Collapse | Copy Code
var $j = jQuery.noConflict();
// Use jQuery via jQuery(...)
$j(document).ready(function(){
   $j("div").hide();
});
Q14. Is there any difference between body onload() and document.ready() function?

Ans: document.ready() function is different from body onload() function for 2 reasons.
We can have more than one document.ready() function in a page where we can have only one body onload function.
document.ready() function is called as soon as DOM is loaded where body.onload() function is called when everything gets loaded on the page that includes DOM, images and all associated resources of the page.

Q15. What is the difference between .js and .min.js?

Ans: jQuery library comes in 2 different versions Production and Deployment. The deployment version is also known as minified version. So .min.js is basically the minified version of jQuery library file. Both the files are same as far as functionality is concerned. but .min.js is quite small in size so it loads quickly and saves bandwidth.

Q16. Why there are two different version of jQuery library?

Ans: jQuery library comes in 2 different versions.
Production
Deployment
The production version is quite useful at development time as jQuery is open source and if you want to change something then you can make those changes in production version. But the deployment version is minified version or compressed version so it is impossible to make changes in it. Because it is compressed, so its size is very less than the production version which affects the page load time.

Q17. What is a CDN?

Ans: A content delivery network or content distribution network (CDN) is a large distributed system of servers deployed in multiple data centers across the Internet. The goal of a CDN is to serve content to end-users with high availability and high performance.

Q18. Which are the popular jQuery CDN? and what is the advantage of using CDN?

Ans: There are 3 popular jQuery CDNs.
1. Google.
2. Microsoft
3. jQuery.
Advantage of using CDN.
It reduces the load from your server.
It saves bandwidth. jQuery framework will load faster from these CDN.
The most important benefit is it will be cached, if the user has visited any site which is using jQuery framework from any of these CDN

Q19. How to load jQuery from CDN?

Ans: Below is the code to load jQuery from all 3 CDNs.
Code to load jQuery Framework from Google CDN
 Collapse | Copy Code
<script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
Code to load jQuery Framework from Microsoft CDN
 Collapse | Copy Code
<script type="text/javascript"
    src="http://ajax.microsoft.com/ajax/jquery/jquery-1.9.1.min.js">
</script>
Code to load jQuery Framework from jQuery Site(EdgeCast CDN)
 Collapse | Copy Code
<script type="text/javascript"
    src="http://code.jquery.com/jquery-1.9.1.min.js">
</script>
Q20. How to load jQuery locally when CDN fails?

Ans: It is a good approach to always use CDN but sometimes what if the CDN is down (rare possibility though) but you never know in this world as anything can happen.

Below given jQuery code checks whether jQuery is loaded from Google CDN or not, if not then it references the jQuery.js file from your folder.
 Collapse | Copy Code
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined')
{
  document.write(unescape("%3Cscript src='Scripts/jquery.1.9.1.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>
It first loads the jQuery from Google CDN and then check the jQuery object. If jQuery is not loaded successfully then it will references the jQuery.js file from hard drive location. In this example, the jQuery.js is loaded from Scripts folder.

Q21. What are selectors in jQuery and how many types of selectors are there?

Ans: To work with an element on the web page, first we need to find them. To find the html element in jQuery we use selectors. There are many types of selectors but basic selectors are:

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

Q22. How do you select element by ID in jQuery?

Ans: To select element use ID selector. We need to prefix the id with "#" (hash symbol). For example, to select element with ID "txtName", then syntax would be,
 Collapse | Copy Code
$('#txtName')
Q23. What does $("div") will select?

Ans: This will select all the div elements on page.

Q24. How to select element having a particular class (".selected")?

Ans: $('.selected'). This selector is known as class selector. We need to prefix the class name with "." (dot).

Q25. What does $("div.parent") will select?

Ans: All the div element with parent class.

Q26. What are the fastest selectors in jQuery?

Ans: ID and element selectors are the fastest selectors in jQuery.

Q27. What are the slow selectors in jQuery?

Ans: class selectors are the slow compare to ID and element.

Q28. How jQuery selectors are executed?

Ans: Your last selectors is always executed first. For example, in below jQuery code, jQuery will first find all the elements with class ".myCssClass" and after that it will reject all the other elements which are not in "p#elmID".
 Collapse | Copy Code
$("p#elmID .myCssClass");
Q29. Which is fast document.getElementByID('txtName') or $('#txtName').?

Ans: Native JavaScipt is always fast. jQuery method to select txtName "$('#txtName')" will internally makes a call to document.getElementByID('txtName'). As jQuery is written on top of JavaScript and it internally uses JavaScript only So JavaScript is always fast.

Q30. Difference between $(this) and 'this' in jQuery?

Ans: this and $(this) refers to the same element. The only difference is the way they are used. 'this' is used in traditional sense, when 'this' is wrapped in $() then it becomes a jQuery object and you are able to use the power of jQuery.
 Collapse | Copy Code
$(document).ready(function(){
    $('#spnValue').mouseover(function(){
       alert($(this).text());
  });
});
In below example, this is an object but since it is not wrapped in $(), we can't use jQuery method and use the native JavaScript to get the value of span element.
 Collapse | Copy Code
$(document).ready(function(){
    $('#spnValue').mouseover(function(){
       alert(this.innerText);
  });
});
Q31. How do you check if an element is empty?

Ans: There are 2 ways to check if element is empty or not. We can check using ":empty" selector.
 Collapse | Copy Code
$(document).ready(function(){
    if ($('#element').is(':empty')){
       //Element is empty
  }
});
And the second way is using the "$.trim()" method.
 Collapse | Copy Code
$(document).ready(function(){
    if($.trim($('#element').html())=='') {
       //Element is empty
  }
});
Q32. How do you check if an element exists or not in jQuery?

Ans: Using jQuery length property, we can ensure whether element exists or not.
 Collapse | Copy Code
$(document).ready(function(){
    if ($('#element').length > 0){
       //Element exists
  });
});
Q33. What is the use of jquery .each() function?

Ans: The $.each() function is used to iterate over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is an object or an array.

Q34. What is the difference between jquery.size() and jquery.length?

Ans: jQuery .size() method returns number of element in the object. But it is not preferred to use the size() method as jQuery provide .length property and which does the same thing. But the .length property is preferred because it does not have the overhead of a function call.

Q35. What is the difference between $('div') and $('<div/>') in jQuery?

Ans: $('<div/>') : This creates a new div element. However this is not added to DOM tree unless you don't append it to any DOM element.

$('div') : This selects all the div element present on the page.

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

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

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

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

get() return a DOM element. The method retrieve the DOM elements matched by the jQuery object. But as it is a DOM element and it is not a jQuery-wrapped object. So jQuery functions can't be used. Find out more here.

Q38. How do you implement animation functionality?

Ans: The .animate() method allows us to create animation effects on any numeric CSS property. This method changes an element from one state to another with CSS styles. The CSS property value is changed gradually, to create an animated effect.

Syntax is:
 Collapse | Copy Code
(selector).animate({styles},speed,easing,callback)
styles: Specifies one or more CSS properties/values to animate.
duration: Optional. Specifies the speed of the animation.
easing: Optional. Specifies the speed of the element in different points of the animation. Default value is "swing".
callback: Optional. A function to be executed after the animation completes.
Simple use of animate function is,
 Collapse | Copy Code
$("btnClick").click(function(){
  $("#dvBox").animate({height:"100px"});
});
Q39. How to disable jQuery animation?

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

Q40. How do you stop the currently-running animation?

Ans: Using jQuery ".stop()" method.

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

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

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

.remove(): Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

.detach(): This method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.

Find out more here

Q42. Explain .bind() vs .live() vs .delegate() vs .on()

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

.bind(): This is the easiest and quick method to bind events. But the issue with bind() is that it doesn't work for elements added dynamically that matches the same selector. bind() only attach events to the current elements not future element. Above that it also has performance issues when dealing with a large selection.

.live(): This method overcomes the disadvantage of bind(). It works for dynamically added elements or future elements. Because of its poor performance on large pages, this method is deprecated as of jQuery 1.7 and you should stop using it. Chaining is not properly supported using this method.

.delegate(): The .delegate() method behaves in a similar fashion to the .live() method, but instead of attaching the selector/event information to the document, you can choose where it is anchored and it also supports chaining.

.on(): Since live was deprecated with 1.7, so new method was introduced named ".on()". This method provides all the goodness of previous 3 methods and it brings uniformity for attaching event handlers.

Find out more here

Q43. What is wrong with this code line "$('#myid.3').text('blah blah!!!');"

Ans: The problem with above statement is that the selectors is having meta characters and to use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\\.bar").
So the correct syntax is,
 Collapse | Copy Code
$('#myid\\.3').text('blah blah!!!');

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

Ans: jQuery provides clone() method which performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes.
 Collapse | Copy Code
$(document).ready(function(){
  $('#btnClone').click(function(){
     $('#dvText').clone().appendTo('body');
     return false;
  });
});
Q45. Does events are also copied when you clone any element in jQuery?

Ans: As explained in previous question, using clone() method, we can create clone of any element but the default implementation of the clone() method doesn't copy events unless you tell the clone() method to copy the events. The clone() method takes a parameter, if you pass true then it will copy the events as well.
 Collapse | Copy Code
$(document).ready(function(){
   $("#btnClone").bind('click', function(){
     $('#dvClickme').clone(true).appendTo('body');
  });

Q46. What is difference between prop and attr?

Ans: attr(): Get the value of an attribute for the first element in the set of matched elements. Whereas,.prop(): (Introduced in jQuery 1.6) Get the value of a property for the first element in the set of matched elements.

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

attr() gives you the value of element as it was defines in the html on page load. It is always recommended to use prop() to get values of elements which is modified via javascript/jquery , as it gives you the original value of an element's current state. Find out more here.

Q47. What is event.PreventDefault?

Ans: The event.preventDefault() method stops the default action of an element from happening. For example, Prevents a link from following the URL.

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

Ans: event.preventDefault(): Stops the default action of an element from happening.
event.stopPropagation(): Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. For example, if there is a link with a click method attached inside of a DIV or FORM that also has a click method attached, it will prevent the DIV or FORM click method from firing.

Q49. What is the difference between event.PreventDefault and "return false"?

Ans: e.preventDefault() will prevent the default event from occurring, e.stopPropagation() will prevent the event from bubbling up and return false will do both.

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

Ans: event.stopPropagation() allows other handlers on the same element to be executed, while event.stopImmediatePropagation() prevents every event from running. For example, see below jQuery code block.
 Collapse | Copy Code
$("p").click(function(event){
  event.stopImmediatePropagation();
});
$("p").click(function(event){
  // This function won't be executed
  $(this).css("background-color", "#f00");
});
If event.stopPropagation was used in previous example, then the next click event on p element which changes the css will fire, but in case event.stopImmediatePropagation(), the next p click event will not fire.

Q51. How to check if number is numeric while using jQuery 1.7+?

Ans: Using "isNumeric()" function which was introduced with jQuery 1.7.

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

Ans: Using $.type(Object) which returns the built-in JavaScript type for the object.

Q53. How do you attach a event to element which should be executed only once?

Ans: Using jQuery one() method. This attaches a handler to an event for the element. The handler is executed at most once per element. In simple terms, the attached function will be called only once.
 Collapse | Copy Code
$(document).ready(function() {
    $("#btnDummy").one("click", function() {
        alert("This will be displayed only once.");
    });
});​
Q54. Can you include multiple version of jQuery? If yes, then how they are executed?

Ans: Yes. Multiple versions of jQuery can be included in same page.

Q55. In what situation you would use multiple version of jQuery and how would you include them?

Ans: Well, it is quite possible that the jQuery plugins which are used are dependent on older version but for your own jQuery code, you would like to use newer version. So because of this dependency, multiple version of jQuery may required sometimes on single page.

Below code shows how to include multiple version of jQuery.
 Collapse | Copy Code
<script type='text/javascript' src='js/jquery_1.9.1.min.js'></script>

<script type='text/javascript'>
 var $jq = jQuery.noConflict();
</script>

<script type='text/javascript' src='js/jquery_1.7.2.min.js'></script>
By this way, for your own jQuery code use "$jq", instead of "$" as "$jq" refers to jQuery 1.9.1, where "$" refers to 1.7.2.

Q56. Is it possible to hold or delay document.ready execution for sometime?

Ans: Yes, its possible. With Release of jQuery 1.6, a new method "jQuery.holdReady(hold)" was introduced. This method allows to delay the execution of document.ready() event. document.ready() event is called as soon as your DOM is ready but sometimes there is a situation when you want to load additional JavaScript or some plugins which you have referenced.
 Collapse | Copy Code

$.holdReady(true);
$.getScript("myplugin.js", function() {
     $.holdReady(false);
});
Q57. What is chaining in jQuery?

Ans: Chaining is one of the most powerful feature of jQuery. In jQuery, Chaining means to connect multiple functions, events on selectors. It makes your code short and easy to manage and it gives better performance. The chain starts from left to right. So left most will be called first and so on.
 Collapse | Copy Code
​$(document).ready(function(){
    $('#dvContent').addClass('dummy');
    $('#dvContent').css('color', 'red');
    $('#dvContent').fadeIn('slow');
});​
The above jQuery code sample can be re-written using chaining. See below.
 Collapse | Copy Code
​$(document).ready(function(){
    $('#dvContent').addClass('dummy')
          .css('color', 'red')
          .fadeIn('slow');    
});​
Not only functions or methods, chaining also works with events in jQuery. Find out more here.

Q58. How does caching helps and how to use caching in jQuery?

Ans: Caching is an area which can give you awesome performance, if used properly and at the right place. While using jQuery, you should also think about caching. For example, if you are using any element in jQuery more than one time, then you must cache it. See below code.
 Collapse | Copy Code
$("#myID").css("color", "red");
//Doing some other stuff......
$("#myID").text("Error occurred!");

Now in above jQuery code, the element with #myID is used twice but without caching. So both the times jQuery had to traverse through DOM and get the element. But if you have saved this in a variable then you just need to reference the variable. So the better way would be,
 Collapse | Copy Code
var $myElement = $("#myID").css("color", "red");
//Doing some other stuff......
$myElement.text("Error occurred!");

So now in this case, jQuery won't need to traverse through the whole DOM tree when it is used second time. So in jQuery, Caching is like saving the jQuery selector in a variable. And using the variable reference when required instead of searching through DOM again.

Q59. You get "jquery is not defined" or "$ is not defined" error. What could be the reason?

Ans: There could be many reasons for this.
You have forgot to include the reference of jQuery library and trying to access jQuery.
You have include the reference of the jQuery file, but it is after your jQuery code.
The order of the scripts is not correct. For example, if you are using any jQuery plugin and you have placed the reference of the plugin js before the jQuery library then you will face this error.
Find out more here.
Q60. How to write browser specific code using jQuery?

Ans: Using jQuery.browser property, we can write browser specific code. This property contains flags for the useragent, read from navigator.userAgent. This property was removed in jQuery 1.9.

Q61. Can we use jQuery to make ajax request?

Ans: Yes. jQuery can be used for making ajax request.

Q62. What are various methods to make ajax request in jQuery?

Ans: Using below jQuery methods, you can make ajax calls.
load() : Load a piece of html into a container DOM
$.getJSON(): Load JSON with GET method.
$.getScript(): Load a JavaScript file.
$.get(): Use to make a GET call and play extensively with the response.
$.post(): Use to make a POST call and don't want to load the response to some container DOM.
$.ajax(): Use this to do something on XHR failures, or to specify ajax options (e.g. cache: true) on the fly.
Find out more here.

Q63. Is there any advantage of using $.ajax() for ajax call against $.get() or $.post()?

Ans: By using jQuery post()/ jQuery get(), you always trust the response from the server and you believe it is going to be successful all the time. Well, it is certainly not a good idea to trust the response. As there can be n number of reason which may lead to failure of response.

Where jQuery.ajax() is jQuery's low-level AJAX implementation. $.get and $.post are higher-level abstractions that are often easier to understand and use, but don't offer as much functionality (such as error callbacks). Find out more here.

Q64. What are deferred and promise object in jQuery?

Ans: Deferred and promise are part of jQuery since version 1.5 and they help in handling asynchronous functions like Ajax. Find out more here.

Q65. Can we execute/run multiple Ajax request simultaneously in jQuery? If yes, then how?

Ans: Yes, it is possible to execute multiple Ajax request simultaneously or in parallel. Instead of waiting for first ajax request to complete and then issue the second request is time consuming. The better approach to speed up things would be to execute multiple ajax request simultaneously.

Using jQuery .when() method which provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events. Find out more here.

Q66. Can you call C# code-behind method using jQuery? If yes,then how?

Ans: Yes. We can call C# code-behind function via $.ajax. But for do that it is compulsory to mark the method as WebMethod.

Q67. Which is the latest version of jQuery library?

Ans: The latest version (when this post is written) of jQuery is 1.10.2 or 2.0.3. jQuery 2.x has the same API as jQuery 1.x, but does not support Internet Explorer 6, 7, or 8.

Q68. Does jQuery 2.0 supports IE?

Ans: No. jQuery 2.0 has no support for IE 6, IE 7 and IE 8.

Q69. What are source maps in jQuery?

Ans: In case of jQuery, Source Map is nothing but mapping of minified version of jQuery against the un-minified version. Source map allows to debug minified version of jQuery library. Source map feature was release with jQuery 1.9. Find out more here.

Q70. How to use migrate jQuery plugin?

Ans: with release of 1.9 version of jQuery, many deprecated methods were discarded and they are no longer available. But there are many sites in production which are still using these deprecated features and it's not possible to replace them overnight. So jQuery team provided with jQuery Migrate plugin that makes code written prior to 1.9 work with it.

So to use old/deprecated features, all you need to do is to provide reference of jQuery Migrate Plugin. Find out more here.

Q71. Is it possible to get value of multiple CSS properties in single statement?

Ans: Well, before jQuery 1.9 release it was not possible but one of the new feature of jQuery 1.9 was .css() multi-property getter.
 Collapse | Copy Code
var propCollection = $("#dvBox").css([ "width", "height", "backgroundColor" ]);
In this case, the propCollection will be an array and it will look something like this.
 Collapse | Copy Code
{
  width: "100px",
  height: "200px",
  backgroundColor: "#FF00FF"
}
Q72. How do you stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements?

Ans: It can be done via calling .stop([clearQueue ] [, jumpToEnd ]) method and by passing both the parameters as true.

Q73. What is finish method in jQuery?

Ans: The .finish() method stops all queued animations and places the element(s) in their final state. This method was introduced in jQuery 1.9.

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

Ans: The .finish() method is similar to .stop(true, true) in that it clears the queue and the current animation jumps to its end value. It differs, however, in that .finish() also causes the CSS property of all queued animations to jump to their end values, as well.

Q75. Consider a scenario where things can be done easily with javascript, would you still prefer jQuery?

Ans: No. If things can be done easily via CSS or JavaScript then You should not think about jQuery. Remember, jQuery library always comes with xx kilobyte size and there is no point of wasting bandwidth.

Q76. Can we use protocol less URL while referencing jQuery from CDNs?

Ans: Yes. Below code is completely valid.
 Collapse | Copy Code
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Q77. What is the advantage of using protocol less URL while referencing jQuery from CDNs?

Ans: It is quite useful when you are moving from HTTP to HTTPS url. You need to make sure that correct protocol is used for referencing jQuery library as pages served via SSL should contain no references to content served through unencrypted connections.

"protocol-less" URL is the best way to reference third party content that’s available via both HTTP and HTTPS. When a URL’s protocol is omitted, the browser uses the underlying document’s protocol instead. Find out more here.

Q78. What is jQuery plugin and what is the advantage of using plugin?

Ans: A plug-in is piece of code written in a standard JavaScript file. These files provide useful jQuery methods which can be used along with jQuery library methods. jQuery plugins are quite useful as its piece of code which is already written by someone and re-usable, which saves your development time.

Q79. What is jQuery UI?

Ans: jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library that can be used to build interactive web applications.

Q80. What is the difference between jQuery and jQuery UI?

Ans: jQuery is the core library. jQueryUI is built on top of it. If you use jQueryUI, you must also include jQuery.

Note: If you have any questions to add to this list then please put it comments. We will be glad to add them in this list. We will be keep on updating this list with new questions and share the updates on our Facebook or Twitter channel. If you are not following us then request you to please follow and stay updated.
What is Jquery?


JQuery is Java Script library or Java Script Framework which helps in how to traverse HTML documents, do some cool animations, and add Ajax interaction to any web page. It mainly helps programmer to reduce lines of code as huge code written in Java Script, can be done easily with JQuery in few lines.

For detailed information, check below link.
http://bit.ly/v0QdsH

Click below link to get mostly asked jQuery interview question.
http://jquerybyexample.blogspot.com/2011/08/mostly-asked-jquery-interview-questions.html

What does dollar Sign ($) means in JQuery?


Dollar Sign is nothing but it's an alias for JQuery. Take a look at below jQuery code

$(document).ready(function(){

});


Over here $ sign can be replaced with "jQuery " keyword.
jQuery(document).ready(function(){

});


Click below link to get mostly asked jQuery interview question.
http://jquerybyexample.blogspot.com/2011/08/mostly-asked-jquery-interview-questions.html

How is body onload() function is different from document.ready() function used in jQuery?


Document.ready() function is different from body onload() function because off 2 reasons.

1. We can have more than one document.ready() function in a page where we can have only one onload function.
2. Document.ready() function is called as soon as DOM is loaded where body.onload() function is called when everything gets loaded on the page that includes DOM, images and all associated resources of the page.

Click below link to get mostly asked jQuery interview question.
http://jquerybyexample.blogspot.com/2011/08/mostly-asked-jquery-interview-questions.html

What are the steps you need to follow to use jQuery in ASP.Net project?


It's really simple. One just need to add reference of javascript file(.js). Go to Jquery.com and download the latest version of jQuery. When download is completed, there is a "jQuery-1.3.2.js" in the folder. Include this file

<script src="_scripts/jQuery-1.3.2.js" type="text/javascript"></script>

and you good to go now for JQuery.

Note : 1.3.2 denotes the library version.. It can be vary depending upon the version of Jquery you download.

Click below link to get mostly asked jQuery interview question.
http://jquerybyexample.blogspot.com/2011/08/mostly-asked-jquery-interview-questions.html

What is JQuery UI?


JQuery UI is a library which is built on top of JQuery library. JQuery UI comes with cool widgets, effects and interaction mechanism.

See below page on this site. Date Picker control used in this page to select date is an example of JQuery UI.

http://www.dotnetfunda.com/misc/topperformers.aspx

Click below link to get mostly asked jQuery interview question.
http://jquerybyexample.blogspot.com/2011/08/mostly-asked-jquery-interview-questions.html

What are features of JQuery or what can be done using JQuery?


Features of Jquery
1. One can easily provide effects and can do animations.
2. Applying / Changing CSS.
3. Cool plugins.
4. Ajax support
5. DOM selection events
6. Event Handling

Click below link to get mostly asked jQuery interview question.
http://jquerybyexample.blogspot.com/2011/08/mostly-asked-jquery-interview-questions.html

Name some of the methods of JQuery used to provide effects?


Some of the common methods are :

1. Show()
2. Hide()
3. Toggle()
4. FadeIn()
5. FadeOut()

Visit my blog.
http://jquerybyexample.blogspot.com/

JQuery is replacement of Java Script?


NOTE: This is objective type question, Please click question title for correct answer.

What are the different type of selectors in Jquery?


There are 3 types of selectors in Jquery
1. CSS Selector
2. XPath Selector
3. Custom Selector

Visit my blog.
http://jquerybyexample.blogspot.com/

What are the advantages of JQuery ?




There are many advantages with JQuery. Some of them are :

. It is more like a JavaScript enhancement so there is no overhead in learning a new syntax.

. It has the ability to keep the code simple, readable, clear and reusable.

. It would eradicate the requirement for writing complex loops and DOM scripting library calls.

How can you select all elements in a page using jQuery?


To select all elements in a page, we can use all selectors, for that we need to use *(asterisk symbol).

<script language="javascript" type="text/javascript">

         $("*").css("border", "2px dotted red");

</script>


The above code will select all elements of the web page and apply border width as 2 pixel, style as dotted and color as red.


Thanks and Regards
Akiii

What is jQuery?


jQuery is not a language but it is a well written JavaScript code, As quoted on official jQuery website “it is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.“

In order to work with jQuery you should be aware of basics of JavaScript, HTML and CSS.
It was released in January 2006 at BarCamp NYC by John Resig.

Licensing:
It is free, open source software Dual-licensed under the MIT License and the GNU General Public License. Microsoft has integrated jQuery officially into its IDE Visual Studio 2010 and jQuery intellisense is available in Visual Studio 2010 now.

Why jQuery?


jQuery is very compact and well written JavaScript code that increases the productivity of the developer by enabling them to achieve critical UI functionality by writing very less amount of code.

It helps to

# Improve the performance of the application
# Develop most browser compatible web page
# Implement UI related critical functionality without writing hundreds of lines of codes
# Fast
# Extensible – jQuery can be extended to implement customized behavior

Other advantages of jQuery are

# No need to learn fresh new syntax's to use jQuery, knowing simple JavaScript syntax is enough
# Simple and Cleaner code, no need to write several lines of codes to achieve complex functionality.

Where to download jQuery from?


jQuery javascript file can be downloaded from jQuery Official website

http://www.jquery.com/

How to use jQuery?


jQuery usually comes as a single JavaScript file containing everything comes out of the box with jQuery. It can be included within a web page using the following mark-up:

To load local jQuery file
<script type="text/javascript" src="jQuery-1.4.1-min.js"></script>


Ideally this markup is kept in under <head></head> tag of your web page, however you are free to keep anywhere you want.

Do I need to refer jQuery file both in Master page/base page/template page and content page?


No, master page/base page/ template page basically helps to create consistent layout for the page in the application. In case you have referred the jQuery file in master page/base page/ template page that cause rendering the file in the browser, you do not need to refer jQuery file the content page again.

In summary, there should not be more than one <script> tag with jQuery file reference in the source code of the rendered web page in the browser.

What is the difference between jQuery-x.x.x.js and jQuery.x.x.x-min.js


In terms of functionality, there is no difference between the jQuery-x.x.x.js and jQuery-x.x.x-min.js (also called minified version). However this can play a vital role in the performance of the web page.

How it affects the performance?
jQuery-1.4.4.js file size is 178 KB as against its minified version jQuery-1.4.4-min.js that is only 76.7 KB in size. So when your page loads in the client?s browser if you are not using minified version, it loads 178 KB file that takes more time to load than 76.7 KB.

Which version of jQuery file should be used?


In most of the recent releases so far, the core functionality of jQuery remains same however some more cool and better features are added. Ideally you should use the latest jQuery files available on the jQuery.com website. By doing this you ensure that your earlier functionality will still work and you can use new features available as part of the new release.

What is CDN?


CDN Stands for Content Distribution Network or also called Content Delivery Network is a group of computers placed at various points connected with network containing copies of data files to maximize bandwidth in accessing the data. In CDN a client access a copy of data nearer to the client location rather than all clients accessing
from the one particular server. This helps to achieve better performance of data retrieval by client.

There are two leading CDNs available that hosts jQuery files.

Microsoft - To load jQuery from Microsoft AJAX CDN
jQuery file can be loaded from Microsoft AJAX CDN. For more details, go to http://www.asp.net/ajaxlibrary/cdn.ashx. You will need to keep following tags in your page.

<script type="text/javascript" language="Javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.1.min.js"></script>


Google - To load jQuery from Google Libraries API

jQuery file can be loaded from Google CDN for more details, go to http://code.google.com/apis/libraries/devguide.html. You will need to keep following tag in your page.
<script type="text/javascript" language="Javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>


Why to load jQuery file from CDN?


You may ask that if we can load the jQuery file from our own server why to load it from the CDNs. The answer is logical and very simple. The browser behavior is that whenever it loads any webpage, it keeps related files (eg. Javascript file, CSS file and Images) used for that page into its cache (also called history). When next time the user browses any web page, browser loads only those files that are new or modified and is not available in the browser cache or history. In this way, browser improves its performance and loads the page.

The possibility is that if more and more websites are using CDNs, the user might have already browsed some other web pages that is using CDNs jQuery file and that file may have into browser cache; so when user browse your page and you are also using CDNs file, the older cached version of jQuery file will be used. In this way your page will load faster as browser will not have to load the jQuery file for your page again.

The benefit
1. Faster page load as jQuery file need not to be downloaded
2. Saves your bandwidth as jQuery file is not loaded from your server
3. Scalable - generally CDNs place these files on the servers located at different geographical locations of the world so that they load faster so irrespective of from where your user is browsing your page, your application runs well.
What if the latest jQuery version is available and I am still referring older version of jQuery file from CDNs?


Do not worry about it, it?s a general promise made by CDNs that they will remain hosting the older version of the files on the same location where they had initially released; so even if newer version of the files are released, the older version remains there on the CDNs and your web page still works.

How to load local jQuery file in case CDN is not available?


Sometimes, it may happen that the CDN you have used to load the jQuery file is not available (it rarely happens, however anything is possible, isn?t it?); in that case you should load your local jQuery file that is available on your server so that all jQuery related functionality still work on your page.

Write following lines of code

<!-- START - jQuery Reference -->
<script type="text/javascript" language="Javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.1.min.js "></script>

<script type='text/javascript'>//<![CDATA[

if (typeof jQuery == 'undefined') {

document.write(unescape("%3Cscript src='/Script/jquery-1.4.1.min.js' type='text/javascript' %3E%3C/script%3E"));

}//]]>

</script>

<!-- END - jQuery Reference -->

Replace bolded path with your own jQuery file path on the server. In the above code, first line tries to load the jQuery file from CDN, if browser could load the file successfully, “jQuery” variable will not be undefined and next script will not run otherwise next script will run that will write the script tag to load the jQuery file from your server.

How to execute jQuery code?


1. As and when page loads, execute the jQuery code

 <script language="javascript" type="text/javascript">

           $(function () {

           $("#div1").css("border", "2px solid green");

            });

            </script>

OR

   <script language="javascript" type="text/javascript">

                     $("#div1").css("border", "2px solid green");

                </script>


The benefit of executing jQuery code in this way is that it doesn?t wait the whole page to load completely, so in case you want user to see the effects as soon as the corresponding elements are loaded, you can use this.

However the disadvantage is that if the element on which jQuery has to execute has not loaded then it will error out or you will not get desired result; so while using this way of executing jQuery code, you will have to make sure that the element on which you want to work with jQuery is loaded first (you can place your jQuery code right after your HTML element).

2. Execute jQuery only when the complete DOM objects (the complete page has been loaded). You will have to wrap your code in .ready function.

<script language="javascript" type="text/javascript">

               $(document).ready(function () {

                   $("#div1").css("border", "2px solid green");

   });

</script>


This is the better and safer way to execute jQuery. This makes sure that jQuery code will execute only if complete page has been loaded in the browser so you are rest assured that user will not see any undesired behavior on the page.

As a developer, the decision of where and how to write jQuery code lies on you. I prefer to use 2nd method as it ensures that my complete page is loaded in the browser and I am ready to play with any element available on the page.

jQuery Core


jQuery accepts a string enclosed with double quote (“”) that can contain a CSS selector which is used to match a set of elements on the web page.

jQuery code can start with either “jQuery” word or a “$” (dollar symbol). Take a look at below code snippet

<script language="javascript" type="text/javascript">

                  $(function () {

                       jQuery("#div1").css("border", "2px solid red");

                       });

</script>


OR

<script language="javascript" type="text/javascript">

          $(function () {

                  $("#div1").css("border", "2px solid green");

           });

</script>


Both above code snippets are functionally same and do the same thing. So you can either user jQuery or $ when you are writing jQuery code.

How to give alert message in jQuery on a Button Click ?


Hi all,
First, include jQuery in your application.

Drop a textbox in your .aspx page:-
<input id="inputField" type="text" size="12"/>


include a button also:-
<asp:Button ID="Button1" runat="server" Text="get"/>


Now, here's the script:-


<script type="text/javascript">

        $(document).ready(function () {

            $('#Button1').click(function () {

                alert($('#inputField').attr("value"));

            });

        });

</script>


On the click of the button, an alert will be given containing the text in the text box.

I hope this helps......
Thanks and Regards
Akiii

What are Selectors in jQuery mean ?


Generally in HTML, if we need to work with any control on a web page we need to find the control. For that we use document.getElementByID or document.getElementByName. But in jquery we do it using Selectors.

Using this selectors we can select all the controls as well using a symbol (* )

A sample code snippet can be of this form

<script language="javascript" type="text/javascript">

$("*").css("border", "10px red");

</script>


This will make all the borders in the web page with a width of 10 pixel and color as red.

Is it good to load jquery from CDN(Content delivery network) ?


Yes, it is always good to load your jquery from content delivery network. It provides some benefits like :-
(1) Caching - It means that if any previously visited site by user is using jQuery from Google CDN then the cached version will be used. It will not be downloaded again.
(2) Reduces load - It reduces the load on your web server as it downloads from Google server's.

Example :-

<script  type="text/javascript"

    src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">

</script>


Thanks and Regards
Akiii

Do we need to add the JQuery file both at the Master page and Content page as well?


No, if the Jquery file has been added to the master page then we can access the content page directly without adding any reference to it.

This can be done using this simple example

<script type="text/javascript" src="jQuery-1.4.1-min.js"></script>


What is the advantage of using the minified version of JQuery rather than using the conventional one?


The advantage of using a minified version of JQuery file is Efficiency of the web page increases.

The normal version jQuery-x.x.x.js has a file size of 178KB

but the minified version jQuery.x.x.x-min.js has 76.7 KB.

The reduction in size makes the page to load more faster than you use a conventional jQuery file with 178KB

What is CDN and how jQuery is related to it?


CDN - It stands for Content Distribution Network or Content Delivery Network.

Generally, a group of systems at various places connected to transfer data files between them to increase its bandwidth while accessing data. The typical architecture is designed in such a way that a client access a file copy from its nearest client rather than accessing it from a centralized server.

So we can load this jQuery file from that CDN so that the efficiency of all the clients working under that network will be increased.

Example :

We can load jQuery from Google libraries API

<script type="text/javascript" language="Javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>


Can we select a element having a specific class in jQuery ?


Yes, we can select an element with a specific class, we use the class selector.The class name must contain the prefix as "." (dot).

<script language="javascript" type="text/javascript">

     

         $(".class1").css("border", "2px solid red");


</script>


Above code will select all the elements of the webpage containing the class as "class1" and apply the css style border width as 2 Pixel, style as solid and color as red.

What is the use of Delegate() Method in jQuery?


The delegate() method can be used in two ways.
1) If you have a parent element, and you want to attach an event to each one of its child elements, this delegate() method is used.
Ex:Un-ordered List
Instead of attaching an event to each <li> element, you can attach a single event to <ul> element.

Example:

$("ul").delegate("li", "click", function(){

$(this).hide();

});


2) When an element is not available on the current page, this method is used.
.live() method is also used for the same purpose but, delegate() method is a bit faster.

Example:

$("ul").delegate("li", "click", function(){

$(this).hide();

});


This will hide any list items that are not currently available on the page. They may be loaded via an Ajax request and then append to it.
Using .bind() or .click() methods, you would have to manually attach events to these new list items once they are added.

Which sign does jQuery use as a shortcut for jQuery?


NOTE: This is objective type question, Please click question title for correct answer.

JQuery is a client scripting.


NOTE: This is objective type question, Please click question title for correct answer.

Can be used JQuery with AJAX?


NOTE: This is objective type question, Please click question title for correct answer.

JQuery is JavaScript Library or JSON Library?


JQuery is a javascript library not JSON Library. Jquery library is single JavaScript file that contains Common DOM, event effects and Ajax functions.

"JQuery is a library of javascript function."

For more Info: http://jquery.com/

What does .size() method of jquery return ?


.size() method of jquery returns number of element in the object. That means that you can count the number of elements within an object.

For example :-

$(document).ready(function(){

 var Count = $("div").size();

 alert(Count);

});



Thanks and Regards
Akiii

What is the difference between jquery.size() and jquery.length ?


jquery.size() and jquery.length both returns the number of element found in the object. But, jquery.length is faster than jquery.size() because size() is a method but length is a property .

So, there is always an overhead in calling a function.


Thanks and Regards
Akiii

How to set Page Title using jQuery ?

$(function(){

   $(document).attr("title", "Dotnet Funda");

});




Thanks and Regards
Akiii

How will you Encode/Decode URL in jQuery ?


In jquery, you can use the following functions to encode and decode url :-

encodeURIComponent(url) and decodeURIComponent(url)


You have to pass the complete url with parameterized value in the function and in return it will encode/decode you url for you
What is the use of jQuery Connect?


It is used to connect or bind a function to another function.It is use to execute a function whenever
a function from another object is executed.

e.g.

function FirstFunction(){

this.Func1 = function(){

       execute1 = 'A class';

      }

}

var firstFunc = new FirstFunction();



function SecondFunction(){

 this.Func2 = function(){

 execute2 = 'Another Class';

 }

}

var secondFunc = new SecondFunction();

$.connect(firstFunc,'Func1',secondFunc,Func2);


In this case whevever we invoke secondFunc.Func2,firstFunc.Func1 will also gets executed indicating that
Func2 of object secondFunc has been associated/ connected to Func1 of object firstFunc

What is the use of jQuery disconnect?


It is used to disconnect a function to another function.It is the opposite of $.connect.

e.g.

$.disconnect(firstFunc,'Func1',secondFunc,Func2);


will disconnect Func1 from Func2 where Func1 is the reference function and Func2 is connected one.

What is the use of jQuery disconnectAll?


It is used to disconnect all the connected functions.

e.g.

$.disconnectAll(firstFunc,'Func1');


will disconnect all the connected function from the reference function Func1.

What are the minimal/must steps needed to execute JQuery?


1.Wait for the DOM of the page to be ready.
2.Finds the appropriate HTML elements that needs to be acted on by using selector.
3.Add event handlers.

e.g.

//Step 1: Wait for the DOM of the page to be ready.

$(document).ready(function ()

{

//Step 2: Finds the appropriate HTML elements that needs to be acted on by using selector

var btnObject = $('#btnSayHello');



//Step 3: Add event handlers (Here click events)

btnObject.click(function ()

{

alert("Hello World...My First JQuery Program");

});

});


How to debug JQuery?


1.Placing debugger keyword

Add the keyword debugger to the line from where we want to start the debugging and then run the Visual Studio in Debug mode by pressing F5 or using the Debug button.

e.g.
<script language ="javascript">

$(document).ready(function ()

{

   var btnObject = $('#btnSayHello');

   debugger;

    btnObject.click(function ()

   {

       alert("Hello World...My First JQuery Program");

   });

});

</script>


2.Inserting a break point after attaching worker process

Press ALT + CTRL + P or tools -> AttachProcess then choose w3wp.exe .

What are the ways by which we can include JQuery in our page?


1.Refer to a local copy using the <script> tag
2.Refer to a remote copy on JQuery.com or the remote copy in the Google AJAX API
3.Refer to a local copy using Script Manager Control
4.Refer to an embedded script using the ClientScript object

How to invoke Jquery function from code behind?


Suppose we want to change the background color of a div tag from the code behind upon button click.In code behind write the below

protected void btnChangecolor_Click(object sender, EventArgs e)

{

string script = "<script type=\"text/JavaScript\" language=\"javascript\">ChangeDivBackgroundcolor();</script>";

 Page.ClientScript.RegisterStartupScript(this.GetType(), "ChangeColor", script);

 }


The aspx file will be as under

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

<script type="text/javascript" src="Scripts/jquery-1.7.2.js"></script>

<script type="text/javascript">

function ChangeDivBackgroundcolor()

{

var divObject = $('#divTest');

divObject.css("background-color", "cyan");

}

</script>

</head>

<body>

<form id="form1" runat="server">

<div>


<asp:Button ID="btnChangecolor" runat="server" Text="Say Hello" onclick="btnChangecolor_Click" />

 </div>

<div id="divTest">Change the color of this div</div>

</form>

</body>

</html>


What is the significance of document.ready()?


It indicates that the DOM of the page is ready and we can start manipulating the DOM elements even though other parts
of the page content(e.g. images/other external resources) are not fully loaded.As soon as the DOM is loaded,
everything inside the (document).ready() should be load even before the page contents are loaded.

Why is JQuery faster than Javascript at execution time?


The onLoad function for the window object executes after the entire page is fully loaded.Untill DOM tree is completely created and all images/other associated resources (like audio files,video files etc) are fully loaded,this onLoad function is never executed and hence the script execution needs to wait till the page is loaded.

But the document.ready() method of JQuery indicates that the DOM of the page is ready and we can start manipulating the DOM elements even though other parts of the page content(e.g. images/other external resources) are not fully loaded.As soon as the DOM is loaded, everything inside the (document).ready() should be load even before the page contents are loaded.

It is because of this reason that JQuery code runs faster

Difference between jQuery-x.x.x.js and jQuery.x.x.x min.js?


In terms of functionality, there is no difference between the jQuery-x.x.x.js and jQuery-x.x.x-min.js .jQuery-x.x.x-min.js is also called as minified version of jQuery.

jQuery-1.4.4.js file size is 178 KB and the jQuery-1.4.4-min.js size is 76.7 KB. If you are not using minified version of jQuery,then it will load the 178 kb file( jQuery-1.4.4.js).So it will take the much time to load the page and will hurt the performance.

So we can prefer using jQuery-1.4.4.js during development and jQuery-1.4.4-min.js when we move the code into production environment.

What is the purpose of jquery-x.x.x-vsdoc.js?


Generally we will use jQuery-x.x.x-vsdoc.js to provide the intellisense support. We can even delete this file. But the thing is that it won't provide the intellisense support if we delete that file.

Which one is the right way to get the TextBox value with id="txtbox" in Jquery?


NOTE: This is objective type question, Please click question title for correct answer.

Differentiate between jquery's ready and holdReady?


jQuery's ready is an event which gets triggered automatically when DOM is ready while holdReady is a signal/flag to hold this triggering. holdReady was included in 1.6 version and it works only if used before the execution/triggering of ready event. Once ready event is fired, it has nothing to do. It is useful in dynamically loading scripts before the ready starts. It release ready event execution when used with a true parameter.

Who is the Inventor of Jquery ?


NOTE: This is objective type question, Please click question title for correct answer.

What is the Scripting technique of JQuery library ?


NOTE: This is objective type question, Please click question title for correct answer.

In JQuery, the function used to execute the starting point of the code is ?


NOTE: This is objective type question, Please click question title for correct answer.

In JQuery, the function used to specify our own character instead of '$' is ?


NOTE: This is objective type question, Please click question title for correct answer.

In JQuery, the method used to select the class of an element is ?


NOTE: This is objective type question, Please click question title for correct answer.

In JQuery, the method used to select an Id of an element is ?


NOTE: This is objective type question, Please click question title for correct answer.

In JQuery, the function used to check whether the element is empty or not ?


NOTE: This is objective type question, Please click question title for correct answer.

In JQuery, the method used to create a new 'div' element is ?


NOTE: This is objective type question, Please click question title for correct answer.

In JQuery, the method used to stop the default action of the event from triggering is ?


NOTE: This is objective type question, Please click question title for correct answer.

In JQuery, the method used to prevent the event from bubbling up the 'DOM' is ?


NOTE: This is objective type question, Please click question title for correct answer.

In JQuery, the method that executes the first event handler and stops the remaining from being executed is ?


NOTE: This is objective type question, Please click question title for correct answer.

In Jquery, the method used to perform the custom animation of a set of css properties is ?


NOTE: This is objective type question, Please click question title for correct answer.

In JQuery, the method used to stop the running animation is ?


NOTE: This is objective type question, Please click question title for correct answer.

In Jquery, the method used to check the data type of any variable is ?


NOTE: This is objective type question, Please click question title for correct answer.

In JQuery, the method used to attach a handler to an event that should execute only once ?


NOTE: This is objective type question, Please click question title for correct answer.

In Jquery, the process of connecting multiple functions and events on selectors,that makes the code shorter and gives better performance is ?


NOTE: This is objective type question, Please click question title for correct answer.

In JQuery, the method used to stop all the queued animations and places the elements in their final state is ?


NOTE: This is objective type question, Please click question title for correct answer.

In JQuery, the method used to provide sliding animation effect to an element is ?


NOTE: This is objective type question, Please click question title for correct answer.

In JQuery, the method used to return all the sibling elements of each list element is ?


NOTE: This is objective type question, Please click question title for correct answer.

In JQuery, the method used to provide the fade effect is ?


NOTE: This is objective type question, Please click question title for correct answer.

In JQuery, the method used to represent an array or object in serialized manner is ?


NOTE: This is objective type question, Please click question title for correct answer.

In JQuery, the method used to hold or release the execution of ready event is ?


NOTE: This is objective type question, Please click question title for correct answer.

In Jquery, the method used to bind a function with another function is ?


NOTE: This is objective type question, Please click question title for correct answer.

In JQuery, the method used to attach a handler to an event of an element is ?


NOTE: This is objective type question, Please click question title for correct answer.

In JQuery, the method used to create a copy of the set of matched elements is ?


NOTE: This is objective type question, Please click question title for correct answer.

What is the basic syntax of jQuery?


Syntax of jQuery:
$(selector).action()

Where $ sign indicates to define or access jQuery,
(selector) indicates to "query (or find)" our HTML elements and,
jQuery action() indicates to be performed on any controls.

How to hide current element or controls in jQuery?


We have to pass this keyword in selector as it indicates current object in Dot Net and hide is an in-build method which is used to Hide any controls from Page.

For Example:-
$(this).hide();



How to hide all Paragraph embedded on the Page?


We have to pass P which is basically a paragraph in selector then call Hide method to hide Paragraph then it will hide all the paragraph elements on the Page.

For Example:-
$("p").hide();


How to hide particular control using jQuery?


If we want to use any control id then we have to use # Sign folloed by ControlID in the Selector.
Suppose,i have a button with id btnValidate and i want to hide this button,so i will write below code:-

$("#btnValidate").hide();

Now,btnValidate will be hidden from Page.

How to hide all controls which have the same class applied?


We will pass class name(dot as prefix) in the selector,which will check all controls which have the same class applied then will hide them from Page.

Suppose,i have a class named button_border written on the Page or File,then i will write as:-
$(".button_border").hide();


What do we mean by #id Selector?


The jQuery #id selector is nothing but a controlID which uses the id attribute of an HTML tag to find the specific control.It must be unique on a page.
We have to use # sign followd by ControlID yo find control usng jQuery.

Syntax:-
$("#anyControlID")
For Example:-
<asp:Button ID="btnDelete" runat="server" Text="Delete"/>

<asp:Button ID="btnSave" runat="server" Text="Save"/>


$(document).ready(function(){

  $("button").click(function(){

    $("#btnDelete").hide();

  });

});


Here,on clicking of save button,Delete button will be hidden.

What do we mean by element or control Selector?


The jQuery element selector is used to select any controls based on the control name.

For Example:-
We can select all division tag or H1 tag elements on a page as below:-
$("div")

$("h1")


What do we mean by .class Selector?


The jQuery class selector searches any controls with a particular class.We have to write a dot character followed by class name in selector tag as below:
$(".name_of_the_class_name")

For Example:-
$(".button_border")

Where,button_border is our class name.

How to disable Browser Back button through jQuery?


Write below line of code:-
<script type="text/javascript" language="javascript">

$(document).ready(function() {

     window.history.forward(1);

     //OR

     window.history.forward(-1);

});

</script>


How to disable mouse right click using jQuery?


First, include the jQuery library in head section like below:-
<script src = "Jquery-1.8.0.min.js" type = "text/JavaScript"></script>

Now write below code:-
<script type="text/JavaScript">

$(function()

{

  $(this).bind(“contextmenu”, function(e)

  {

    e.preventDefault();

  });


});

</script>


How to disable cut,copy & paste in TextBox using jQuery?


Write Below code on ASPX page:-
<script type="text/javascript">

$(document).ready(function ()

{

   $('#txt_employee_code').bind('copy paste cut',function(e)

   {

       e.preventDefault();

   });


});

</script>


What is the action of blind effect in Jquery and how to apply blind effect in Jquery?


The blind effect hides/shows an element by wrapping the element in a container, and "pulling the blinds"

Example:
The code should be written with in the body html and body tags.
For applying this blind effect we should give a link of jquery version

This is the link of jquery version

 <script src="//code.jquery.com/jquery-1.10.2.js"></script>

  <script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>


<link rel="stylesheet"

    href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">


  <style>

  #toggle {

    width: 300px;

    height: 100px;

    background: black;

    background:white;

  }

  </style>




<p>Click here for the action.</p>

<div id="toggle"></div>



<script>

$( document ).click(function() {

  $( "#toggle" ).toggle( "blind" );

});

</script>


How to use a fold effect in Jquery ?


In order to show /hides an element folding in the Html page ..
For example :
Here this code should be written with in Html and body tags
For this Fold effect we should give a link of Jquery Version to run this effect
Css should be written with in the script


This is the Link of Jquery version.
 <script src="//code.jquery.com/jquery-1.10.2.js"></script>

  <script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>


 <link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">

 

    <body>

   <style>



  div {

    width: 600px;

    height: 150px;

    background: blue;

    border: 2px solid black;

  }

  </style>




 <button>Fold</button>

<div></div>



<script>

    $("button").click(function () {

        $("div").toggle("fold", 1000);

    });

</script>


How to fade an element in the Jquery?


This fade action Hides/shows an element in jquery in the html page.

Example:

This is the version of Jquery written with in the script

<script src="//code.jquery.com/jquery-1.10.2.js"></script>

  <script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>



This is the link of stylesheet and a link of Jquery:

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">


Code for the Fade function
<style>

  #Fade {

    width: 300px;

    height: 150px;

    color:white;

    background-color:blue;

  }

  </style>

        <p>Click around box for the action </p>

     

        <div id="Fade">Hide the text box</div>


        <script>

    $(document).click(function () {

        $("#Fade").toggle("fade");

    });

        </script>


In Jquery how do we use the effect of drag and drop function in html?


This drag and drop function is used to show the text elements on the drop box to highlight.
Example:

The code should be written in html and body tags.

The source code of Jquery should be written in Code

  <script src="//code.jquery.com/jquery-1.10.2.js"></script>

  <script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>


Link Should me mentioned in the style sheet to run the function of the effect.


 <link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">  


The code of the effect is

<style>

  #Drag {

    width: 150px;

    height: 150px;

    background: royalblue;

  }

  #Drop {

    position: relative;

    left: 250px;

    top: 0;

    width: 250px;

    height: 250px;

    background: green;

    color: white;

    padding: 20px;

  }

  </style>






<div id="Drop">Written text is dropped her</div>

<div id="Drag">HEllo the text is written in this box</div>



<script>

    $("#Drag").draggable();

    $("#Drop").droppable({

        drop: function () {

            alert("dropped");

        }

    });

    </script>


What is selector ?


To find the html element in jQuery we use selectors... and
to work with an element on the web page, first we need to find them for this purpose we
use selectors in Jquery

For Example :


<script language="javascript" type="text/javascript">

$("*").css("border", "2px solid brown");

</script>


here in the above code ("*") stare is called selector

How do we select all selectors in Jquery in a page ?


We use (*)asterisk symbol to select all the selectors in the page
for example
 <script language="text/javascript">

$("*").css("border", "2px dashed brown");

</script>


What function we must use to select a particular element having a specific class and how do we define it ?


class selector is used to select an element with a specific class
We need to use / we define it by the class name with “.” (dot) ex- (.class)
for example :
<script language="javascript" type="text/javascript">

$(".class").css("border", "2px solid brown");

</script>


What is the specific type elements to select elements in Jquery?


Element selector is used to select an element with a specific type.
for example :
<script language="javascript" type="text/javascript">

$("p").css("border", "5px solid green");

</script>

in this "P"(paragraph) is the element.

What function for ID selector we must use to select an element in jquery . and how do we define it ?


ID selector can be usedto select an element having a specific id,
We need to prefix the id with “#” (hash symbol).

For example :

<script language="javascript" type="text/javascript">

$("#p").css("border", "5px solid  brown");

</script>


How do we execute progressbar in jquery?


By giving the code called
$( "#processbar" ).progressbar({

  value: false

});

this should be written in script tags
we should mentioned the div name as we have given in the class
<div id="processbar"></div>


For example:
This is the link of the jquery version
 <link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css"/>


This should be written in body tags

 <script src="//code.jquery.com/jquery-1.10.2.js"></script>

  <script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>




         <div id="processbar"></div>

         <script>





             $("#processbar").progressbar({

                 value: false

             });

         </script>


How to show a seekerbar/slider in jquery?


By giving a class called slider in jquery
 <script>

             $("#seekerbar").slider();

               

         </script>

div name should me mentioned as same in the script
<div id="seekerbar"></div>

for example:
This is the vresion of jquery

 <link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css"/>



This should be written with in the body tags

 <script src="//code.jquery.com/jquery-1.10.2.js"></script>

  <script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>

         <div id="seekerbar"></div>

         <script>

             $("#seekerbar").slider();

               

         </script>
NOTE: This is objective type question, Please click question title for correct answer.

.How do we append the source element content to the target ?


NOTE: This is objective type question, Please click question title for correct answer.

How to append html content to the element ?


NOTE: This is objective type question, Please click question title for correct answer.

How to insert html content at the begining of an element ?


NOTE: This is objective type question, Please click question title for correct answer.

How to insert html content from the begining of the target ?


NOTE: This is objective type question, Please click question title for correct answer.

How to remove the css class from an element ?


NOTE: This is objective type question, Please click question title for correct answer.

How to remove an attribute class from an element ?


NOTE: This is objective type question, Please click question title for correct answer.

How to get/set the value of an element ?


NOTE: This is objective type question, Please click question title for correct answer.

How to add an element to a pirticular element ?


NOTE: This is objective type question, Please click question title for correct answer.

How to iterate through each specified element of the page ?


NOTE: This is objective type question, Please click question title for correct answer.

How to find a specific element from the group of similar kinds of element ?


NOTE: This is objective type question, Please click question title for correct answer.

How to filter an element from the group of similar kind of elements based on its attribute value ?


NOTE: This is objective type question, Please click question title for correct answer.

How do we find first element in Jquery from the matched element ?


NOTE: This is objective type question, Please click question title for correct answer.

How do we find last element in Jquery from the matched element ?


NOTE: This is objective type question, Please click question title for correct answer.

How to find the immediate next element from the element found by the selector ?


NOTE: This is objective type question, Please click question title for correct answer.

How do we place content before a specific element ?


NOTE: This is objective type question, Please click question title for correct answer
How to get or set element width in the Jquery whta is the method used ?


NOTE: This is objective type question, Please click question title for correct answer.

How to insert an element after a specific element ?


NOTE: This is objective type question, Please click question title for correct answer.

How to insert an element before a specific element ?


NOTE: This is objective type question, Please click question title for correct answer

jQuery interview questions and answers


Part 1   Part 2   Part 3   Part 4   Part 5

<<Previous  Next>>

1.What is jQuery Selectors? Give some examples.
2. How can we give face effect in jQuery?
3. Explain the animate function.
4. What is .siblings() method in jQuery?
5. Explain width() vs css(‘width’).
6. What is the use of jQuery.data()?
7. Explain bind() vs live() vs delegate() methods.
8. Explain the each() function.
9. Explain slideToggle() effect.
10. What is difference between $(this) and ‘this’ in jQuery?
11. What is the use of param() method.
12. What is jQuery.holdReady() function?
13. Explain .empty() vs .remove() vs .detach().
14. How to read, write and delete cookies in jQuery?
15. Is window.onload is different from document.ready()?
16. What is Chaining in jQuery?
17. What is difference between sorting string array and sorting numerical array in jQuery?
18. What is difference between prop and attr?
19. How to always reference latest version of jQuery?
20. What is resize() function in jQuery?

21.What is jQuery?

Latest answer: jQuery is a lightweight JavaScript library that emphasizes interaction between JavaScript and HTML.............
Read answer

22.Advantages of jQuery

Latest answer: The advantages of using jQuery are: JavaScript enhancement without the overhead of learning new syntax............
Read answer

23.Explain the features of jQuery.

Latest answer: Features of jQuery are :

Effects and animations
Ajax
Extensibility.............
Read answer
24.Explain the concepts of "$ function" in jQuery with an example.

Latest answer: The type of a function is "function".
There are a lot of anonymous functions is jquery...............
Read answer

25.Why is jQuery better than javascript?

Latest answer: jQuery is great library for developing ajax based application.
It helps the programmers to keep code simple and concise and reusable..............
Read answer

26.Explain how jQuery Works.

Latest answer: <html>
     <head>
     <script type="text/javascript" src="jquery.js"></script>
     <script type="text/javascript">................
Read answer

27.When can you use jQuery?

Latest answer: JQuery can be used to

apply CSS
call functions on events
traverse the documents...................
Read answer

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());
});
Web Services in C# The Circular Stack, An Advance in D ... Abstract Class & Interface: Two Vil ...

READER LEVEL: ARTICLE
 Sachin Kalia
 81  1,854
jQuery Interview Questions and Answers With Practices: Part 2
Posted by Sachin Kalia in Articles | JQuery on May 21, 2014
In this article, you will learn jQuery interview questions and answers.
Follow @dotnetpiper
Tweet
inShare

0 28446
Download Files:JQueryInterview2.rar
Kindly visit the first part of the jQuery interview questions and answers.

Interview question and answer
jQuery Interview Question and Answers With Practices: Part 1

Question What are selectors in jQuery?

AnswerjQuery is one of the main features of jQuery. Because until we won't fetch elements from the DOM we are unable to perform further actions.
jQuery Selectors are used to select one or a group of HTML elements from your web page.
jQuery selectors always start with a dollar sign and parentheses: $()
There are some ways 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: $(“#div1”)

It will select a single element that has an ID of div1.

3. Select elements by class

Example: $(“.even”)

It will select all the elements having a class even as shown in sample applications also.

An example of basic selectors are as shown in the following image:

selectors

There are some more selectors that are listed below and very useful from a jQuery perspective.
$('*'): This selector selects all elements in the document.
$("p > *"): This selector selects all elements that are children of a paragraph element.
$("li:not(.myclass)"): Selects all elements matched by <li> that do not have class="myclass".
$("ul li:first"): This selector gets only the first <li> element of the <ul>.
$(":empty"): Selects all elements that have no children.
$("p:empty"): Selects all elements matched by <p> that have no children.
$("div[p]"): Selects all elements matched by <div> that contain an element matched by <p>.
$("p[.myclass]"): Selects all elements matched by <p> that contain an element with a class of myclass.
[attr] has attributes like type, value, href and id.
[attr=val] has attribute with value val.
[attr!=val] does not have attribute with value val.
[attr^=val] attribute begins with val.
[attr$=val] attribute ends with val.
[attr*=val] attribute includes val.
[attr~=val] attribute includes val as a word.
[attr|=val] attribute begins with val and optional hyphen.
Question What is jQuery.holdReady() function?

Answer By using the jQuery.holdReady() function we can hold or release the execution of jQuery's ready event. This method should be called before we run the ready event. To delay the ready event, we need to call jQuery.holdReady(true);

When we want to release the ready event then we need to call jQuery.holdReady(false);

This function is helpful when we want to load any jQuery plugins before the execution of the ready event or want to perform certain events/functions before document.ready() loads. For example some information also.
For example:

holdReady

Question What is chaining in jQuery?

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

Chaining reduces the code segment and keeps it very clean and easy to understand. Generaly chaining uses the jQuery built in functions that makes compilation a bit faster.

By using chaining we can write the code above as follows:
 $(document).ready(function () {
         $("#div2").html($("#txtBox").prop("readonly")) + '</br>';
         $("#div3").html($("#txtBox").attr("readonly"));
});
The code segment above is described by the image below:

chaining

Question What are the fastest selectors in jQuery?

Answer ID and element selectors are the fastest selectors in jQuery.
Question What are the slow selectors in jQuery?

Answer Class selectors are slow compared to ID and element.

Question How jQuery selectors are executed?

Answer Your last selectors are always executed first. For example, in the following jQuery code, jQuery will first find all the elements with class ".list" and then it will select all the elements with the id "li#first-li".

$('p').html($("li#first-li.list").text());
jQuery selectors executed
Question Which is the fastest, document.getElementByID('txtName') or $('#txtName').?

Answer Native JavaScipt is always fast. The jQuery method to select txtName "$('#txtName')" will internally make a call to document.getElementByID('txtName'). Since jQuery is written on top of JavaScript and it internally uses JavaScript only, JavaScript is always fast.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
Jquery
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 suing 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
JQuery Interview Question Answer
1- What is jQuery ?
It's very simple but most valuable Question on jQuery means jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, animating, event handling, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript. Jquery is build library for javascript no need to write your own functions or script jquery all ready done for you

2- How you will use Jquery means requirement needed for using jquery?
Nothing more need to do just olny download jquery library(.js file) from any of the jquery site Download jquery and just linked with your html pages like all other javascript file

like below :
Code:
< script src="jquery.js" language="javascript" type="text/javascript">

3- what the use of $ symbol in Jquery?
$ Symbol is just replacement of jquery means at the place of $ you may use jquery hence $ symbol is used for indication that this line used for jquery

4- How do you select an item using css class or ID and get the value by use of jquery?
If an element of html like < div> , < p> or any tag have ID MyId and class used MyClass then we select the element by below jquery code

Code:
$('#MyId') for ID and for classs $('.MyClass')
and for value
Code:
var myValue = $('#MyId').val();
// get the value in var Myvalue by id
Or for set the value in selected item
Code:
$('#MyId').val("print me");
// set the value of a form input

5- How to get the server response from an AJAX request using Jquery?
When invoking functions that have asynchronous behavior We must provide a callback function to capture the desired result. This is especially important with AJAX in the browser because when a remote request is made, it is indeterminate when the response will be received.
Below an example of making an AJAX call and alerting the response (or error):
Code:
$.ajax({
     url: 'pcdsEmpRecords.php',
     success: function(response) {
        alert(response);
     },
     error: function(xhr) {
        alert('Error!  Status = ' + xhr.status);
     }
});

6- How do you update ajax response with id " resilts"?
By using below code we can update div content where id 'results' with ajax response
Code:
function updateStatus() {
     $.ajax({
            url: 'pcdsEmpRecords.php',
            success: function(response) {
             // update div id Results
             $('#results').html(response);
         }
     });
}

7- How do You disable or enable a form element?
There are two ways to disable or enable form elements.
Set the 'disabled' attribute to true or false:
Code:
// Disable #pcds
$('#pcds').attr('disabled', true);
// Enable #pcds
$('#pcds').attr('disabled', false);
Add or remove the 'disabled' attribute:
// Disable #pcds
$("#pcds").attr('disabled', 'disabled');
// Enable #x
$("#pcds").removeAttr('disabled');

8- How do you check or uncheck a checkbox input or radio button?
There are two ways to check or uncheck a checkbox or radio button.
Set the 'checked' attribute to true or false.
Code:
// Check #pcds
$('#pcds').attr('checked', true);
// Uncheck #pcds
$('#pcds').attr('checked', false);
Add or remove the 'checked' attribute:
// Check #pcds
$("#pcds").attr('checked', 'checked');
// Uncheck #pcds
$("#pcds").removeAttr('checked');

9- How do you get the text value of a selected option?
Select elements typically have two values that you want to access. First there's the value to be sent to the server, which is easy:
Code:
$("#pcdsselect").val();
// => 1
The second is the text value of the select. For example, using the following select box:
Code:
<select id="pcdsselect">
   <option value="1">Mr</option>
   <option value="2">Mrs</option>
   <option value="3">Ms</option>
   <option value="4">Dr</option>
   <option value="5">Prof</option>
</select>
If you wanted to get the string "Mr" if the first option was selected (instead of just "1"), you would do that in the following way:
Code:
$("#mpcdsselect option:selected").text();
// => "Mr"
Smile JQUERY INTERVIEW QUESTIONS AND ANSWERS SET PDF- 1 TOP 30
Hey friends, here are the most commonly asked Jquery interview questions and answers for both experienced and beginners ....
You know in these days Jquery become very popular and in every interview you will defiantly face question related to Jquery/javascript, Interviewer must ask Jquery questions.. So be prepare before attend your interview...
And I see many Jquery user want to download .PDF as these questions ans answers set. So In next article I will provide PDF file with 50 Jquery Questions answers.
This is Set-1 containing Top 30 most commonly/impotent Jquery questions with answers:

1).What is Jquery?
jquery is javascript library which required a jquery.js file. After that you can write the jquery as fallows. It uses "$" as the short hand to write jquery code.
Simple Syntax is
Code:
$(document).ready(function()
{
    function body
});

2).When Jquery founded and by whome?
It was released in January 2006 at BarCamp NYC by John Resig(Jquery founder).


3).What scripting language is jQuery written in?
Ans: JavaScript


4).Write a basic code for add jquery library to pages?
Code:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
// You can write the code here
</script>
</head>
<body>
<a href="http://www.tutoriz.com/">Jquery Interview Questions and Answers</a>
</body>
</html>


5).What is jQuery Selectors? Give some examples.
Ans: Selectors are used in jQuery to find out DOM elements. Selectors can find the elements via ID, CSS, Element name and hierarchical position of the element.

Code:
Selector     Example          Selects
*           $("*")          All elements
#id          $("#lastname")      The element with id=lastname
.class          $(".intro")              All elements with class="intro"
element      $("p")          All p elements
For more click here http://www.w3schools.com/jquery/jquery_r...ectors.asp


6).What $("div.tutoriz") will select?
Ans: All the div element with tutoriz class.


7).jQuery uses CSS selectors and XPath expressions to select elements true or false?
Ans:- True


8).What are the fastest selectors in Jquery?
Ans: ID and element selectors are the fastest selectors


9).What are the slower selecoters in Jquery?
Ans: Class selectors are slower

10).Which one is faster Jquery ID selector or JavaScript getElementById()?
(Jquery ID selector vs JavaScript getElementById())
Ans: JavaScript getElementById() is faster than Jquery Id ($("#elementID")) selector


11).Where Jquery code execute? On client browser or server browser?
On client browser



12).Write the code for selecting the
1st div element, 4th div element
last div, and for even and odd div elemets also.
one by one?
apply the red color on the above div.
Code:
<div class="questions">
        <div class="box"> Question</div>
    <div class="box"> Question</div>
    <div class="box"> Question</div>
    <div class="box"> Question</div>
    <div class="box"> Question</div>
    <div class="box"> Question</div>
</div>
Code for first div       : $("div.questions > div:first").css("color", "red");
Code for 4th div         : $("div.questions > div:nth-child(4)").css("color", "red");
Code for last div        : $("div.questions > div:last").css("color", "red");
Code for even div        : $("div.questions > div:even").css("color", "red");
Code for odd div         : $("div.questions > div:odd").css("color", "red");

13).Write the code for select second last div element?
Code for second last div : $("div.questions > div::nth-last-child(2)").css("color", "red"); <!-- Introduced in CSS3 -->

14).What are the advantages of using jQuery over JavaScript in ASP.NET web application
Ans:
Below are the advatages of using jQery over JavaScript
a>.Jquery is well written optimised javascript code so
it will be faster in execution unless we write same standard optimised javascript code.
b>.Jquery is concise java script code ,means minimal ammount of code
is to be written for the same functionality than the javascript.
c>.Javascript related Development is fast using Jquery because most of the
functionality is already written in the library and we just need to use that.
d>.Jquery has cross browser support ,so we save time for supporting all the browsers.


15).What is Chaining in jQuery?
Ans:
In jQuery, Chaining means to connect multiple functions, events on selectors. look at Sample Code 1 and 2.
Code:
Sample Code 1
​$(document).ready(function(){
    $('#dvContent').addClass('dummy');
    $('#dvContent').css('color', 'red');
    $('#dvContent').fadeIn('slow');
});​

Sample Code 2 (using Chaining)
​$(document).ready(function(){
    $('#dvContent').addClass('dummy')
          .css('color', 'red')
          .fadeIn('slow');    
});​
Both the sample codes above will perform the exact same thing but the only difference is that Sample code 2 is using Chaining. But Code 2 is faster and shorter then Code 1.
The problem with the Sample Code 1 is that for every statement, jQuery has to search the entire DOM and find the element and after that executes the attached function on it. But when chaining is used, then jQuery has to find the element only once and it will execute all the attached functions one by one. This is the advantage of Chaining.

16).Is jQuery a library for client scripting or server scripting?
Ans: Client Script

17).What is jQuery & its significance? Why it is so popular?...


18).What are features of JQuery
or
What can be done using JQuery?
Features of Jquery
1. One can easily provide effects and can do animations.
2. Applying / Changing CSS.
3. Cool plugins.
4. Ajax support
5. DOM selection events
6. Event Handling


19).How to check Jquery UI loaded or not?
Ans: // Checking if jQuery UI is loaded or not
Code:
if($.ui){
    // jQuery UI is loaded
}else {
    // jQuery UI is not loaded
}

20).How check currently loaded jQuery UI version on the page?
Ans: // Returns jQuery UI version (ex: 1.8.2) or undefined
$.ui.version


21).Write the code for setting datetimepicker on textbox click.
If below is our textbox
<input type="text" id="abc" name=%26quot%3Bacc%26quot%3B value="Select Date" />
then Jquery code will be
$("#abc").datepicker();



22).If you have a table, how you will apply the two differt color on alternate rows using Jquery?
Code:
<table border="1">
  <tr><td>Vikas Ahlawat</td></tr>
  <tr><td>Edwin George</td></tr>
  <tr><td>Rohit Khurana</td></tr>
  <tr><td>Gyan Singh</td></tr>
</table>
Ans :
<script src="jquery.js"></script>
<script>
$(document).ready(function()
{
  $("tr:even").css("background-color", "#f4f4f8");
  $("tr:odd").css("background-color", "#ffffff");
});
</script>


23).Name the Jquery method which is used to hide selected elements?
Ans: .hide()


24).Name the Jquery methods which are used for apply css class?
Ans:
$("#Id1").addClass('YourClassName'); // for apply class
$("#Id1").removeClass('YourClassName'); // for remove class


25).What is the use of attr() method in Jquery?
The attr() method sets or returns attributes and values of the selected elements.
When this method is used to return the attribute value, it returns the value of the first matched element.
When this method is used to set attribute values, it sets one or more attribute/value pairs for the set of matched elements.
Code:
$(selector).attr(attribute) //it will return the value of an attribute
$(selector).attr(attribute,value) //it will set the value of an attribute
$(selector).attr({attribute:value, attribute:value,...}) //for set multiple attribute

26).Can we use both jQuery and AJAX together?
Ans: yes

27).Tell the name of jQuery method which is used to perform an asynchronous HTTP request?
Ans: jQuery.ajax()

28).What is the use of jquery load() method?
The jQuery load() method is a powerful AJAX method.
The load() method loads data from a server and puts the returned data into the selected element without reload the complate page.
Ex:The following example loads the content of the file "demo_test.txt" into a specific <div> element
$("#div1").load("demo_test.txt");


29).Can we use our own specific charactor in the place of $ sigh in Jquery?
Ans: Yes
You can also create your own shortcut very easily. The noConflict() method returns a reference to jQuery, that you can save in a variable, for later use. Here is an example:
Code:
var vikas = $.noConflict();
vikas(document).ready(function(){
  vikas("button").click(function(){
    vikas("p").text("jQuery is still working!");
  });
});

30).Name the 5 Jquery events?
Ans:-
jQuery Events
jQuery click() event.
jQuery dblclick() event.
jQuery mouseenter() event.
jQuery mouseleave() event.
jQuery mousedown() event.
jQuery mouseup() event.
jQuery hover() event.
jQuery focus() and blur() events.

Please must give your feedback...
Click on the following link to DOWNLOAD .PDF FILE

No comments:

Post a Comment