Google News
logo
jQuery Interview Questions
jQuery is a set of (a rich bundle of) JavaScript libraries that helps users apply dynamic functionality to web pages with great ease. It is designed to simplify the client-side scripting of HTML.
It is very easy to learn and use.
It is used to develop browser compatible web applications.
It improves the performance of an application.
It is very fast and extensible.
It facilitates you to write minimal lines of codes for UI related functions.
It provides a cross-browser support.
These are some effects methods used in jQuery :

show()
hide()
toggle()
fadeIn()
fadeOut()
Easy to learn : jQuery is easy to learn because it supports same JavaScript style coding.
Write less do more : jQuery provides a rich set of features that increase developers' productivity by writing less and readable code.
Excellent API Documentation : jQuery provides excellent online API documentation.
Cross-browser support : jQuery provides excellent cross-browser support without writing extra code.
Unobtrusive :  jQuery is unobtrusive which allows separation of concerns by separating html and jQuery code.
 JavaScript is a language While jQuery is a library built in the JavaScript language that helps to use the JavaScript language.
Dollar Sign is nothing but it's an alias for JQuery. Take a look at below jQuery code.

$(document).ready(function(){
  //script-content
});

Over here $ sign can be replaced with "jQuery" keyword.

jQuery(document).ready(function(){
  //script-content
});
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.
Code to load jQuery from two types of CDNs :
Google CDN : <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Microsoft CDN : <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
The  jQuery library is a client side Scripting.

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

1. Name Selectors - It is used to selects all elements which match with the given element Name. Ex : $("p") ,  $("h1"),  $("h2"), etc.
2. ID(#) Selectors  - It is used to selects a single element which matches with the given ID. Ex : $("#test") 
3. class(.) Selectors - It is used to selects all elements which match with the given Class. Ex : $(".test")

and more selectors please click here!
To deal with cookies in jQuery we have to use the ftl cookie plugin.

1. Create cookie : $.ftl("cookie_name", "cookie_value");
2. Read Cookie : $.ftl("cookie_name");
3. Delete cookie : $.ftl("cookie_name", "remove");
ajax() method is more powerful and configurable, allows you to specify how long to wait and how to handle error, get() is a specialization to over ajax just to retrieve some data.

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.

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 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.
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.
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.
There are many advantages of using jQuery. Some of them include :
 
   It is like an enhanced version of JavaScript so there is no overhead in learning a new syntax.
 
   jQuery has the ability to keep the code simple, readable, clear and reusable.
 
   It has Cross-browser support.
 
   This would remove the requirement for writing complex loops and DOM scripting library calls.
 
   jQuery helps in event detection and handling.
 
   It provides tons of plug-ins for all kind of needs.
he jQuery fadeToggle() method is used to toggle between the fadeIn() and fadeOut() methods. If the elements are faded in, it makes them faded out, and if they are faded out, it makes them faded in.
 
Syntax :
$(selector).fadeToggle();  
$(selector).fadeToggle(speed,callback);   
$(selector).fadeToggle(speed, easing, callback);  
 
speed : It is an optional parameter. It specifies the speed of the delay. Its possible values are slow, fast and milliseconds.
 
easing: It specifies the easing function to be used for transition.
 
callback: It is also an optional parameter. It specifies the function to be called after completion of fadeToggle() effect.
The jQuery delay() method is used to delay the execution of functions in the queue. It is the best method to make a delay between the queued jQuery effects. The jQUery delay () method sets a timer to delay the execution of the next item in the queue.
 
Syntax :

$(selector).delay (speed, queueName) ​

 


speed : It is an optional parameter. It specifies the speed of the delay. Its possible values are slow, fast and milliseconds.
 
queueName : It is also an optional parameter. It specifies the name of the queue. Its default value is "fx" the standard queue effect.
The jQuery html() method is used to change the entire content of the selected elements. It replaces the selected element content with new contents.
 
Syntax :

$(document).ready(function(){    
    $("button").click(function(){    
        $("p").html("Hello <b>freetimelearning.com</b>");    
    });    
});​
    
The jQuery CSS() method is used to get (return)or set style properties or values for selected elements. It facilitates you to get one or more style properties. The jQuery CSS() provides two ways:
 
Return a CSS property

It is used to get the value of a specified CSS property.
 
$(document).ready(function(){    
    $("button").click(function(){    
        alert("Background color = " + $("p").css("background-color"));    
    });    
}); ​
   
 
Set a CSS property

This property is used to set a specific value for all matched element.
 
$(document).ready(function(){    
    $("button").click(function(){    
        $("p").css("background-color", "violet");    
    });    
});  
Yes. You can use any number of document.ready() function on the same page.

Example :
 
$(document).ready(function() {    
$("h1").css("background-color", "red");    
 });    
$(document).ready(function() {    
$("p").css("background-color", "blue");    
 }); 
jQuery filter is used to filter the specific values from the object. It filters the result of your original query into specific elements.
The jQuery serialize() method is used to create a text string in standard URL-encoded notation. It serializes the form values so that its serialized values can be used in the URL query string while making an AJAX request.
 
Syntax :

$(document).ready(function(){    
    $("button").click(function(){    
        $("div").text($("form").serialize());    
    });    
});
The animate function is used to apply the custom animation effect to elements. Syntax :
$(selector).animate({params}, [duration], [easing], [callback])  
Here,
 
* "param" defines the CSS properties on which you want to apply the animation.

* "duration" specify how long the animation run. It can be one of the following values : "slow," "fast," "normal" or milliseconds

* "easing" is the string which specifies the function for the transition.

* "callback" is the function which we want to run once the animation effect is complete.
Whenever an Ajax request completes, jQuery triggers the ajaxComplete event. Any and all handlers that have been registered with the .ajaxComplete() method are executed at this time.
Whenever an Ajax request is about to be sent, jQuery checks whether there are any other outstanding Ajax requests. If none are in progress, jQuery triggers the ajaxStart event. Any and all handlers that have been registered with the .ajaxStart() method are executed at this time.
body.Onload() event will be called only after the DOM and associated resources like images get loaded, but jQuery's document.ready() event will be called once the DOM is loaded and it does not wait for the resources such as images to be loaded.
QUnit is a powerful, easy-to-use JavaScript unit testing framework. It's used by the jQuery, jQuery UI, and jQuery Mobile projects and is capable of testing any generic JavaScript code.
Usually, JS functions and variables use $ as a name. In jQuery, $ is just an alias for jQuery, so we don’t need to use $. If we have to use a JS library along with jQuery, the control of $ is given to the JS library. To give this control, we use jQuery.noConflict(). It is also used to assign a new name to a variable.
 
var newname = jQuery.noConflict();
There are many methods like :
 
.ajaxStart() : register the handler to be called when the first Ajax request begins.
.ajaxStop() : register the handler to be called when all requests are complete.
.ajaxSuccess() : register the handler to be called when an Ajax request is successfully completed..
CSS(‘width’) returns the width value in pixels, whereas width() returns the integer (without the unit values). For example:
 
div{
width: 20cm;
}
If you print the values:
 
$(this).width();
$(this).css(‘width’);
 
you will get the values like 756 and 756px respectively. Note that though we specified width in cm, it is converted to pixel (px) for output purposes.
bind() : this method registers the event handler directly to the required DOM element.
$(“#members a”).bind(“click”, function(f){….});
This means any matching anchors will have this event handler attached!
 
live() : this method attaches the event handler to the root of the document. This means one handler can be used for all events that propagated to the root. The handler is thus attached only once.
 
delegate() : in this method, you can choose where to attach the handler. This is the most efficient and robust method for delegation.
 
Eg:
$(“#members”).delegate(“ul li a”, “click”, function(f){….});
In jquery both works and gives the same result but now the time in current version of jquery we use the jquery.length because jquery.size is depreciated.
 
Below is the some points about this properties :
 
jquery.size() and jquery.length() both returns the number of element in an object.
 
jquery.length() property is faster as compared to jquery.size() method.
 
jquery.length() property prefered compared to size() because it does not have overhead of a function call.
 
Very significant difference is that jquery.size() is depreciated so we always use jquery.length() instead of jquery.size().
 
For Examples: Counts the number of unordered list li on the page to demonstrate the same according to the jQuery documentation.
 
$('li').size();

$('li').length;// faster
 
 It is a plugin/widget that adds datepicker functionality in HTML pages. It is highly configurable and can be customized for date format, language, restricting date selection, etc. Refer to this jQuery documentation for datepicker options.
Map function translates a set of elements into another set of values in a jQuery array that may or may not have the elements. The map is called as :
$(“<element>”).map(<function to execute for elements in the object>)

Grep, on the other hand, finds an element in an array.
jQuery.grep(myArr, function(){}
Both attr() and prop() can be used to set or get an element’s value, however attr() returns the original (default) value whereas prop() returns the most recent (current) value. For example, if a text input had an initial value of ‘Male,’ and later it was changed by the user to ‘female,’ attr() will return the value as ‘Male’ whereas prop() will return the value as ‘female.’
Following are the ways to include jQuery in a page :
 
* Local copy inside script tag
* Remote copy of jQuery.com
* Remote copy of Ajax API
* Local copy of script manager control
* Embedded script using client script object
ID and Element are the fastest selectors in jQuery.
Class selectors are the slowest selectors in jQuery.
Chaining is a  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. Generally chaining uses the jQuery built in functions that makes compilation a bit faster.
 
By using chaining we can write the above code as follows :  

$(document).ready(function() {  
    $("#div2").html($("#txtBox").prop("readonly")) + '</br>';  
    $("#div3").html($("#txtBox").attr("readonly"));  
});  
The parent() function returns the parent of the selected element by calling the jQuery parent() function. The siblings() function returns all the siblings of given HTML elements.
jQuery.holdReady() function is what 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 plugin before the execution of the ready event or want to perform certain events/functions before document.ready() loads .
The resize event occurs when the size of the browser window is changed. jQuery resize() Method attaches window element to an event handler function and this event handler function executes when the resize event occurs.
 
jQuery resize() Method Syntax :
$(window).resize(function(){
 //code that executes when the resize event occurs.
});
The jQuery library has two different versions Development and Production. The other name for the deployment version is minified version. 
 
Considering the functionality, both the files are much similar to each other. Being smaller in size, the  .min.js   gets loaded quickly saving the bandwidth.
Ajax methods trigger an event handler that results in jQuery Ajax Events. Some of the examples of jQuery Ajax Events are as listed below.
 
These events are categorized into local events and global events.
 
1. ajaxStart() : It is a Global Event, This event triggers as a result of starting of an Ajax request, provided no other Ajax request currently running.

2. beforeSend() : It is a Local Event, as the name indicates, this event gets invoked before Ajax request starts, thereby allowing to modify XMLHttpRequest objects.

3. ajaxSend() : It is a Global Event, and this event gets called before the Ajax request is run.

4. success() : It is a Local Event. This event triggers only if the Ajax request was successfully sent ( i.e. while sending Ajax request, the event does not display any error from the server or from data).

5. ajaxSuccess() : It is a Global Event, triggers only if the request sent was successful.

6. error() : It is a Local Event, that gets triggered if an error occurs while executing the request. (You can have either error or a success callback while sending Ajax request)

7. ajaxError() : It is a Global Event, which behaves the same as its local counterpart error() event.

8. complete() : It is a Local Event. This event gets called regardless of the request being successful or result in an error, and complete callbacks are received, even for synchronous requests.

9. ajaxComplete() : It is a Global Event, which behaves the same as its local counterpart complete() event, even for synchronous requests.

10. ajaxStop() : It is a Global Event, that gets triggered when no Ajax requests are still being processed/ pending for processing.
There are few ways in which we can debug jQuery code.
 
Modern-day browsers such as Google Chrome, Mozilla Firefox, Opera and Safari have built-in Javascript debugger. To debug the jQuery code, Press F12 from your keyboard and the browser with the built-in debugger will open a UI, wherein select the ‘Console’ menu. The error will be displayed in the console menu if any.
 
You can write console.log() into the code to get the error text, you can also write debugger; in between the code line, due to debugger the script will start in debug mode, pressing F12 into the browser will open console which will debug the code, pressing F10 will read values of the jQuery objects, and this is how we can debug jQuery code.
jQuery.data() method aids in attaching any type of data to DOM elements, free from memory leaks. jQuery makes sure that data is removed along with the DOM elements removed via jQuery methods.
 
Code for Storing and retrieving data related to an element.
$('#myDiv').data('keyName', { foo : 'bar'});
$('#myDiv').data('keyName'); // { foo : 'bar'}
When a radio button is selected addition check attribute is not added to it. You have to enter "checked".
 
Example :                                          
$(document).ready(function(){
    $("input[type='button']").on('click', function(){
       var radioValue = $("input[name='gender']:checked").val();
       if(radioValue){
          alert(radioValue);
       }
    });
}); 
We can use regex ([0-9]{10})|(\([0-9]{3}\)\s+[0-9]{3}\-[0-9]{4})
1. parent() and parents() are used to select an element’s parent or ancestors.
2. children() is used to select an element’s immediate children.
3. siblings() is used to select all of an element’s surrounding sibling elements.
4. prev() is used to select an element’s immediate preceding sibling.
5. next() is used to select an element’s immediate following sibling.
6. prevAll() is used to select all siblings coming before an element.
7. nextAll() is used to select all siblings coming after an element.
8. not() is used to remove elements from a selection using a selector.
9. eq() is used to zero in on a single element in a selection by providing its offset position within the selection offset from zero.
Tag Name : Represents a tag name available in the DOM. For example $('p') selects all paragraphs <p> in the document.

Tag ID : Represents a tag available with the given ID in the DOM. For example $('#some id') selects the single element in the document that has an ID of some-id.

Tag Class : Represents a tag available with the given class in the DOM. For example $('.some-class') selects all elements in the document that have a class of some class.
To valid email id using JQuery create a separate function ValidEmail(). Pass the email id as a parameter. Using Regex we can valid the email id. Example shown below.
 
function ValidEmail(EmailID) {
var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(EmailID)) {
return true;
}
else {
return false;
}
}
Using JQuery $.extend method we can merge the contents of two or more objects into the first object. The syntax is as follow.
 
var obj-0 = $.extend({}, obj-1, obj-2);
 
Let’s we have two array’s arr-i & arr-j. During development what I need is I want to merge arr-j values to arr-i. In this case jquery extend method helps.
 
$.extend( arr-i, arr-j );
 
But this is not recursive. To merge two objects recursively we need to pass the first parameter value true to extend method. As shown in below.
 
$.extend( true, arr-i, arr-j );
Jquery map method is used to translate items of an Array or object to new array of items. Let’s take an example.
 
var tempArray = { "name":"RamanaReddy", "age":30, "designation":"UI Developer" };
var realArray = $.makeArray( tempArray )
$.map( realArray, function( val, i ) {
// Do something
});
Advertisement