JQuery Interview Questions

Question 1: What is JQuery?

JQuery is a cross-browser lightweight JavaScript library. In simple words jQuery has been designed to make navigation to any element easier, or adding/invoking event handlers on your HTML page and also simplify the way you access the elements in your web pages, provide help in working with client-side events, enable visual effects like animation, and make it easier to use Ajax in your applications.

A quick look at what is available in jQuery:

  • Cross-browser support and detection.
  • AJAX functions
  • CSS functions
  • DOM manipulation
  • DOM transversal
  • Attribute manipulation
  • Event detection and handling.
  • JavaScript animation
  • Hundreds of plugins for pre-built user interfaces, advanced animations, form validation, etc.
  • Expandable functionality using custom plugins.

For more follow the link: Introduction To jQuery

Question 2. What is JQuery.noConflict?

jQuery no-conflict is an option given by jQuery to overcome the conflicts between the different js frameworks or libraries. When we use jQuery no-conflict mode, we are replacing the $ to a new variable and assigning to jQuery some other JavaScript libraries. Also use the $ (Which is the default reference of jQuery) as a function or variable name what jQuery has. And in our development life, we are not at all strict to only jQuery.

Learn more here: JQuery No-Conflict And Using Different Versions Of jQuery

Question 3. What is a CDN?

Content Delivery Network (CDN) in simple terms is a collection of servers spread across the globe. In other words, a CDN is a network of servers in which each request will go to the closest server.

Need For a CDN

For any web application, data can be categorized into either static or dynamic content. Dynamic content is the one that generally comes from a database. Static content is like CSS, images, JavaScript, flash files, video files and so on.

Now one may ask, how are requests served when a user enters a URL into the browser? Interesting, let's have a look at it. Before knowing a CDN and its usage, it is very important to understand this process: What and Why of CDN

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

The basic operation in jQuery is selecting an element in DOM. This is done with the help of $() construct with a string parameter containing any CSS selector expression. $() will return zero or more DOM elements on which we can apply an effect or style.

$(document).ready() indicates that code in it needs to be executed once the DOM got loaded. It won't wait for the images to load for executing the jQuery script. We created an anonymous function inside ready() function to hide div1.

We can rewrite $(document).ready() as jQuery (document).ready(), since $ is an alias for jQuery. Always use jQuery in place of $, if you are using more than one JavaScript library to resolve conflicts with jQuery library. The methods called on $(), will implicitly be applied on all the elements returned by it without need of explicit looping. Let's say, $('.myclass').hide() will hide all elements with class as myclass with implicit looping.

As we discussed earlier, $() accepts a string parameter having tag name [like div, p] or Element Id or class name as shown in the following table:

Selector jQuery Syntax Description
Tag Name $('div') All div tags in the document
ID $('#TextId') Selects element with ID as TextId. It starts with # followed Element Id.
Class $('.myclass') Selects all elements with class as myclass. It starts with '.' followed by class name

For more details read this article: Selectors in jQuery

Question 5. What is the use of jQuery .each() function?

The "jQuery.each()" function is a general function that will loop through a collection (object type or array type). Array-like objects with a length property are iterated by their index position and value. Other objects are iterated on their key-value properties. The "jQuery.each()" function however works differently from the $(selector).each() function that works on the DOM element using the selector. But both iterate over a jQuery object.

Callback method

In the "jQuery.each()" method we're able to pass in an arbitrary array or object in which for each item will have the callback function executed.

The "$.each()" function loops over any type of collection, either an array or an object collection. The "jQuery..each()" function has a callback function in which we pass the indexing value and the corresponding value of each item of the array each time. We can access the value of the current index position in the loop using the "this" keyword and append it in any DOM element.

When you pass the array-like object to the .each() function, the callback can accept two arguments: index of the item, where index is the numerical zero-based index in the array of the current items and item is the value of the current array.

For example: If we pass an array to each function, it iterates over items in the array and accesses both the current item and its index position.

Syntax

jQuery.each(collection, callback(indexInArray, valueOfElement))  
  
<script type = "text/javascript">  
    $(document).ready(function() {  
  
        var arr = ["Goergie", "Johnson", "Agile", "Harrison", "Gaurav"];  
  
        $.each(arr, function(index, value) {  
            alert('Position is : ' + index + ' And Value is : ' + value);  
        });  
        
    });   
</script>

For more details follow the link: $.each() Function in jQuery

Question 6. What is difference between prop and attr?

jQuery.attr()

Gets the value of an attribute for the first element in the set of matched elements.

Whereas:

jQuery. prop ()

Gets the value of a property for the first element in the set of matched elements.

What Attributes actually are

Attributes carry additional information about an HTML element and come in name=”value” pairs. You can set an attribute for an HTML element and define it when writing the source code.

For example

<input id="txtBox" value="Jquery" type="text" readonly="readonly" />

As shown above, “id”, "type” and “value" are attributes of the input elements.

For more details follow the link: Difference Between prop and attr in jQuery

Question 7. What is jQuery UI?

jQuery UI enable our applications to have a cool user interface and animation in a faster way. It is the set of plug-ins that include interface interactions, effects, animations, widgets and themes built on the JavaScript Library. jQuery is used to create cohesive and consistent APIs. It is a method that we can use to extend jQuery prototype objects. By that prototype object you can enable all jQuery objects to inherit any method that you add.

Interactions

We can use interactions for basic mouse-based behaviours to any element. Examples of Interactions are the following:

  • Draggable
  • Droppable
  • Resizable
  • Selectable
  • Sortable

Learn more here: Getting Started With jQuery UI Plugin

Question 8. What are the methods used to provide effects?

jQuery provides many amazing effects, we can apply these effects quickly and with simple configuration. The effect may be hiding, showing, toggling, fadeout, fadein, fadeto and so on toggle(), Show() and hide() methods. Similarly we can use other methods as in the following:

  • animate( params, [duration, easing, callback] ) This function makes custom animations for your HTML elements.
  • fadeIn( speed, [callback] ) This function fades in all the matched elements by adjusting their opacity and firing an optional callback after completion.
  • fadeOut( speed, [callback] ) This function is used to fade out all the matched elements by adjusting their opacity to 0, then setting the display to "none" and firing an optional callback after completion.
  • fadeTo( speed, opacity, callback ) This function fade the opacity of all the matched elements to a specified opacity and firing an optional callback after completion.
  • stop( [clearQueue, gotoEnd ]) This function stops all the currently running animations.

For More Info follow the link: jQuery Effects Methods

Question 9. How we can use jQuery in ASP.NET?

As you know jQuery is a fast, lightweight JavaScript library that is CSS3 compliant and supports many browsers. The jQuery framework is extensible and handles the DOM manipulations, CSS, AJAX, Events and Animations, very nicely.

Some differences between JavaScript and jQuery

JavaScript is a language whereas jQuery is a library written using JavaScript.

Let us go through an example, which will help you in understanding the use of jQuery with ASP.NET application.

Make a folder with the name Scripts inside your application. Right click on Scripts folder > Add Existing Item > Browse to the path where you downloaded the jQuery library (jquery-1.3.2.js) and the intellisense documentation (jquery-1.3.2-vsdoc2.js). Select the files and click Add. The structure will look similar to the following image:

In this example, I am going to display an alert on asp:Button click using jQuery.

Here's the Default.aspx code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
  
<head runat="server">  
    <title>My First Application With JQuery</title>  
  
    <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>  
  
    <script type="text/javascript">  
        $(document).ready(function() {  
            $("#Button1").click(function() {  
                alert("Welcome jQuery !");  
            });  
        });  
    </script>  
  
</head>  
  
<body>  
    <form id="form1" runat="server">  
        <div>  
            <asp:Button ID="Button1" runat="server" Text="Click Me" />  
        </div>  
    </form>  
</body>  
  
</html>

For more code examples follow the link: An Introduction to jQuery with ASP.NET Or Consuming ASP.NET Web Service through jQuery

Question 10. How can we use hide() method on a button click using jQuery?

In jQuery the hide () method is very useful. By using this method you can hide HTML elements with the hide() method. In this example, we create a div element which contains text. When we click on the Button the text we use in the div will be hidden.

Example

We are showing you the complete code for the .aspx page below. 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
  
<head>  
    <title>here</title>  
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>  
    <script type="text/javascript">  
        $(document).ready(function() {  
            $("button").click(function() {  
                $("#div1").hide();  
            });  
        });  
    </script>  
</head>  
  
<body>  
    <h2>  
This is a heading</h2>  
    <div id="div1">  
         jQuery is great library for developing ajax based application.  
        <br> jQuery is great library for the JavaScript programmers, which simplifies the development of web 2.0 applications.  
        <br />  
        <br />  
        <br />  
    </div>  
    <button>  
        Hide</button>  
</body>  
<html> 

For more follow the link: html() and hide() method in jQuery

Question 11. What is the difference between $(window).load and $(document).ready function in jQuery?

$(window).load is an event that fires when the DOM and all the content (everything) on the page is fully loaded. This event is fired after the ready event.

Let's look at an example.

<script type="text/javascript" lang="ja">  
    $(window).load(function() {  
        alert("Window load event fired");  
    });  
  
    $(document).ready(function() {  
        alert("document ready event fired");  
    });  
</script>

In the preceding JavaScript, we created an anonymous function that contains an alert message. So, when the preceding two events are fired an alert window will pop-up.

Run the application and let's see which event is fired first.

The document ready function will be fired first.

 

Then the window load event will be fired.

 

When to use $(window).load instead of $(document).ready

In most cases, the script can be executed as soon as the DOM is fully loaded, so ready() is usually the best place to write your JavaScript code. But there could be some scenario where you might need to write scripts in the load() function. For example, to get the actual width and height of an image.

As we know the $(window).load event is fired once the DOM and all the CSS, images and frames are fully loaded. So, it is the best place to write the jQuery code to get the actual image size or to get the details of anything that is loaded just before the load event is raised.

Follow the link for more details: Basics of jQuery: Part 1

Question 12. How to handle Controls attribute Using jQuery?

For handle Controls attribute using jQuery we used .addClass(), .removeClass(), .css(), .toggleClass(), etc to manage all css and html attributes of any html control.

You can follow the link: Handle Controls Attribute Using jQuery

Question 13: What is chaining 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 code segment above is described by the following image:

Follow the link for more details: jQuery Interview Questions and Answers With Practices: Part 2 Or jQuery - "Write Less Do More": Day 1

Question 14: How to work with parent(), children() and siblings() methods in jQuery?

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.

Learn more here: Getting Started With jQuery Traversing

Question 15. What is jQuery Datepicker in jQuery?

As per jQueryUI Documents, the jQuery UI Datepicker is a highly configurable plugin that adds datepicker functionality to your pages. You can customize the date format and language, restrict the selectable date ranges and add in buttons and other navigation options easily.

By default, the datepicker calendar opens in a small overlay when the associated text field gains focus. For an inline calendar, simply attach the datepicker to a div or span.

You must use the following jQuery reference in your HTML Code, otherwise it will not work.

<head>  
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">  
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>  
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>  
</head>

Display month & year menus in jQuery Datepicker.

HTML

Date : <input id="Datepicker" type="text" />   

jQuery

The following code will show the Month & Year menus in jquery Datepicker. The "yearRange" will specify the range of the year you want.

$(function() {  
  
    $('#Datepicker').datepicker({  
        dateFormat: 'dd/mm/yy',  
        changeMonth: true,  
        changeYear: true,  
        yearRange: '1950:2100'  
  
    });  
  
}) 

For more details follow the link: jQuery Datepicker - Part 2

Question 16. How to use scrolling an ASP.NET Multiline Textbox using jQuery?

We will write the jQuery code which will be inside the <script></script> tag and always placed between head section or body section. Its your choice that where you want to place it. Let's see the jQuery code here:

Explanation

Here we will explain the jQuery code which is given above. When the user clicks on the button (btn), we toggle the click behavior. On the first click, we cancel the postback by using e.preventDefault() and then call a function called s_roll() passing in the textarea and the scrollHeight. The code $txt[0].scrollHeight is for scrolling downwards.

e.preventDefault();  
s_roll($txt, $txt[0].scrollHeight);

Again when the user clicks the button (btn) again, the postback is cancelled and the scrollHeight is set to 0. And by using it the multiline textbox will be scrolling upwards.

e.preventDefault();  
s_roll($txt, 0);  

Here the scrollArea() function accepts the textarea that is to be scrolled as well as the scrollHeight. We then animate the scrollTop property to scroll upwards/downwards depending on the height parameter. The duration of the animation is set to 1000 milliseconds which provides a smooth scrolling effect and you can change according to your requirement. The function is given below which will animate it. 

Learn more here: Advanced Typing Scroller Using jQuery

Question 17. What is Ajax in jQuery?

AJAX stands for “Asynchronous JavaScript and XML”. AJAX is about exchanging data with a server, without reloading the whole page. It is a technique for creating fast and dynamic web pages.

In .NET, we can call server side code using two ways:

  1. ASP .NET AJAX
  2. jQuery AJAX

In this article we will focus on jQuery Ajax.

$.ajax () Method

JQuery’s core method for creating Ajax requests. Here are some jQuery AJAX methods:

  • $.ajax() - Performs an async AJAX request.
  • $.get() - Loads data from a server using an AJAX HTTP GET request.
  • $.post() - Loads data from a server using an AJAX HTTP POST request.

To know more click.

$.ajax () Method Configuration option

Options that we use:

  • async
  • type
  • url
  • data
  • datatype
  • success
  • error

Let’s have a detailed overview:

async

Set to false if the request should be sent synchronously. Defaults to true.

Follow the link for more details: ASP.NET MVC Application - Using jQuery, AJAX

Question 18. Define slideToggle() effect?

The slide methods do the up and down element. To implement slide up and down on element jQuery here are the three methods:

  • slideDown()
  • slideUp()
  • lideToggle()

And how to use them:

1. slideDown() Method

This function is used to slide and hide an element on down side:

<script type="text/javascript">  
    $(document).ready(function() {  
        $("#btnSlideDown").click(function() {  
            $("#login_wrapper").slideDown();  
            return false;  
        });  
    });  
</script> 

2. slideUp() Method

This function is used to slide and show element up side:  

<script type="text/javascript">  
    $(document).ready(function() {  
        $("#btnSlideUp").click(function() {  
            $("#login_wrapper").slideUp();  
            return false;  
        });  
    });  
</script>

3. slideToggle() Method

This method is between slideUp() method and slideDown() method. It shows/hides an element in up/down side:

<script type="text/javascript">  
    $(document).ready(function() {  
        $("#btnSlideToggle").click(function() {  
            $("#login_wrapper").slideToggle();  
            return false;  
        });  
    });  
</script>

For more details follow the link: jQuery Effects using Slide methods

Question 19: What are the advantages of jQuery?

In JavaScript we write more code because it doesn't have more functions like animation effects functions and event handling. So if you use JavaScript, developers write more code and they often feel embrace when they execute the code on the browser and get a problem related to cross-browser support. To solve these types of problems, John has created a JavaScript library with a nice motto, "write less and do more" in 2006; that is called jQuery. So you can use all the functions and other capabilities available in JavaScript. It saves developer's time, testing efforts, lines of code and improves their productivity and efficiency of development. The following are some important points to use jQuery.

  • Fully documented
  • Lot of plugins
  • Small size
  • Everything works in IE 6.0+, FF 2.0+, Safari 3.0+, Chrome and Opera 9.0+

To know more about jQuery follow the link: jQuery Overview

Question 20: Define bind() and unbind elements in jQuery?

The jQuery bind() method attaches an event handler to elements, whereas unbind() detaches an existing event handler from elements. Use basic HTML code to create the HTML elements. 

Learn more here: jQuery Unbind() method to remove an attached event handler

Question 21: How to remove a DOM Element using jQuery?

Sometimes we get a requirement to delete all child nodes and remove DOM elements using jQuery to make a dynamic web page. In this scenario jQuery provides a couple of methods to remove DOM elements. Here are the options:

  • empty()
  • remove()
  • html()

For more details follow the below given link: Remove DOM Elements Dynamically in jQuery Or Remove a DOM Element Using jQuery

Question 22: What are the features of jQuery used in web applications?

jQuery has some important features such as event handling, Ajax support and animation effects functions. Here is the list of important features supported by jQuery.

  1. HTML/DOM Manipulation: JavaScript do not have any features related to the DOM, but JavaScript in the browser does include some intelligence about the DOM.

    Example: GetElementById() function

    DOM is an important feature of jQuery. It defines the logical structure of documents and the way a document is accessed and manipulated. jQuery has the extra intelligence regarding  DOM.
     
  2. Event Handling: jQuery introduced a feature called Event handling. Before starting event handling you need to understand event. Events are actions. This means that you can write code that runs when a user clicks on a certain part of the page, or when mouse is moved over a form element. jQuery contains many events, such as a user clicking on a button, moving a mouse over an element and so on.
     
  3. Ajax Support: For example, when you select an item from a DropDownList or other control on the same page then that can cause loss of data. Ajax is used to update the part of the web page without reloading the page. For example, if you create a search functionality in your website like Google Search. When you enter text into the Search TextBox then without reloading the page you see the related text. You can do it easily using Ajax Methods.
     
  4. Animations in jQuery: The jQuery comes with plenty of built-in animation effects that you can use in your websites. For example, animation, show, hide and so on. In jQuery the animate() method is very useful. By using this method we can change the size of elements.
    • Animation method
    • Show method
    • Hide method

For more details follow link: jQuery Overview

Question 23. What is the use of jQuery filter?

JQuery supports various types of filters, such as:

  1. .eq()
  2. .first()
  3. .last()
  4. .filter()
  5. .has()
  6. .not()

For more details follow link: Filter in jQuery

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

The ajax() method is used to do an AJAX (asynchronous HTTP) request. It provides more control of the data sending and on response data. It allows the handling of errors that occur during a call and the data if the call to the ajax page is successful.

Here is the list of some basic parameters required for jQuery.ajax Method: 

  • type: Specifies the type of request (GET or POST).
  • url: Specifies the URL to send the request to. The default is the current page.
  • contentType: The content type used when sending data to the server. The default is "application/x-www-form-urlencoded".
  • dataType: The data type expected of the server response.
  • data: Specifies data to be sent to the server.
  • success(result,status,xhr): A function to run when the request succeeds.
  • error(xhr,status,error): A function to run if the request fails.

For more details follow link: Introduction to jQuery.ajax Call in ASP.NET

Question 25. What is an attribute in jQuery?

There are many important properties of DOM or HTML elements such as for the <img> tag the src, class, id, title and other properties. jQuery provides ways to easily manipulate an elements attribute and gives us access to the element so that we can also change its properties. 

  1. attr( properties ) - Set a key/value object as properties to all matched elements.
  2. attr( key, fn ) - Set a single property to a computed value, on all matched elements.
  3. removeAttr( name ) - Remove an attribute from each of the matched elements.
  4. hasClass( class ) - Returns true if the specified class is present on at least one of the set of matched elements.
  5. removeClass( class ) - Removes all or the specified class(es) from the set of matched elements.
  6. toggleClass( class ) - Adds the specified class if it is not present, removes the specified class if it is present.
  7. html( ) - Gets the HTML contents (innerHTML) of the first matched element.
  8. html( val ) - Sets the HTML contents of every matched element.
  9. text( ) - Gets the combined text contents of all matched elements.
  10. text( val ) - Sets the text contents of all matched elements.
  11. val( ) - Gets the input value of the first matched element.

Learn more here: jQuery Attribute Basics

Question 26. What are jQuery Events?

When we design dynamic web pages, we need to apply some events such as Mouse Click, for forms submit the form after a button click, change a color after a click, etc. So in layman language, events are actions that are used for dynamic web pages. When we perform these actions on an HTML page, we can do whatever we want.

We use some event handlers to perform the action. Some important handlers are bind(), unbind(), blur(), off(), hover(), on(), one(), ready(), trigger() etc. 

Learn more here: Overview of jQuery Events

Question 27. What is the jQuery Unbind() method?

The jQuery bind() method attaches an event handler to elements, whereas unbind() detaches an existing event handler from elements. Use basic HTML code to create the HTML elements.

For more details follow link: jQuery Unbind() method to remove a attached event handler

Question 28. What is the jQuery Animation?

In short, the .animate method is used to perform a custom animation of a set of CSS properties. The .animate() method comes in two flavours. The first takes four arguments and the second takes two arguments.

For more details follow link: jQuery .animate() Method Part 1

Question 29. How can you find browser and browser version in jQuery?

Using $.browser property of jQuery  returns the browser information.

Using $.browser is not recommended by jQuery itself, so this feature has been moved to the jQuery.migrate plugin which is available for downloading if the user want. It is a vulnerable practice to use the same. Use it only if needed. It is always better to not use browser specific codes.

For more details follow link: Find Browser And Browser Version Using jQuery

Question 30. What is $.each() function in jQuery?

The "jQuery.each()" function is a general function that will loop through a collection (object type or array type). Array-like objects with a length property are iterated by their index position and value. Other objects are iterated on their key-value properties. The "jQuery.each()" function however works differently from the $(selector).each() function that works on the DOM element using the selector. But both iterate over a jQuery object.

For example: If we pass an array to the each() function, it iterates over items in the array and accesses both the current item and its index position.

For more details follow link: $.each() function in jQuery

Question 31: What is the difference between Map and Grep function in jQuery?

In $.map() you need to loop over each element in an array and modify its value whilst the $. Grep() method returns the filtered array using some filter condition from an existing array.

The basic structure of Map() is: $.map ( array, callback(elementOfArray, indexInArray) )

Learn more here: Diifference Between Map and Grep Function in jQuery

Question 32: What are jQuery plugins?

Plugins are a piece of code. In jQuery plugins it is a code written in a standard JavaScript file. These JavaScript files provide useful jQuery methods that can be used along with jQuery library methods.

Any method you use in plugins must have a semicolon (;) at the end. The method must return an object (jQuery), unless explicitly noted otherwise. Use each to iterate over the current set of matched elements. It produces clean and compatible code that way. Prefix the filename with jQuery, follow that with the name of the plugin and conclude with .js. (For example, jquery.plug-in.js). Always attach the plugin to jQuery directly instead of $, so users can use a custom alias via the noConflict() method (via the jQuery Team).

Learn more here: jQuery Plugins

Question 33: Define jQuery .animate() method?

In jQuery the animate() method is very useful. By using this method we can change the size of elements. In this example we will create a div element which contains an Image; when we move the mouse over the image, the image size will change. First of all you add an image to the application, add a new form to the application and add the following HTML code to the aspx page.

<div style="height: 100px; width: 100px; position: relative">  
   <img src="animate.gif" id="img" />  
</div> 

Now add the following code in the head section.

<script type="text/javascript">  
    $(document).ready(function() {  
  
        $("div").mouseover(function() //mouseover function will execute when mouse pointer will reach on <div>element  
            {  
                $("img").animate({  
                    height: 300  
                }, "slow"); //image height will change by using animate method  
                $("img").animate({  
                    width: 300  
                }, "slow");  
                $("img").animate({  
                    height: 100  
                }, "slow");  
                $("img").animate({  
                    width: 100  
                }, "slow");  
            });  
    });  
</script>

In the above code we create a mouseover function.

$("img").animate({ height: 300 }, "slow"); //image height will change by using animate method  
$("img").animate({ width: 300 }, "slow");  
$("img").animate({ height: 100 }, "slow");  
$("img").animate({ width: 100 }, "slow");  

For more follow the link: CSS() and Animate() Method in jQuery

Question 34: What is the difference between bind() and live() method in jQuery ?

The binding of event handlers are the most confusing part of jQuery for many developers working on jQuery projects. Many of them unsure of which is better to use. In this article we will see the main differences between Bind and Live methods in jQuery.

Bind() Method

The bind method will only bind event handlers for currently existing items. That means this works for the current element.

Example

$(document).ready(function () {   
   $('P').bind('click', function () {  
      alert("Example of Bind Method");  
      e.preventDefault();  
   });   
});  

Live() Method
The Live method can bind event handlers for currently existing items or future items.

Example

$(document).ready(function() {  
    $('P').live('click', function() {  
        alert("Example of live method");  
        e.preventDefault();  
    });  
    $('body').append('<p>Adding Future items</p>');  
  
});

Follow the link: Difference Between Bind and Live Methods in jQuery

Question 35: What is jQuery.holdReady() function?

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. For example, some information.

For example

Learn more hereL jQuery Interview Questions and Answers With Practices: Part 2 or HoldReady Functions in jQuery 1.9.1

Question 36: What is resize() function in jQuery?

This method in jQuery is used for changing of the size of the element. You can use by .resize() function. For more visit the following link: Changing Size of The Text Using jQuery

Question 37: Define Add or Remove class in jQuery?

addclass will be used for adding a new CSS class after replacing the old class and removeClass will work for removing the selected class.

$(document).ready(function() {    
    $('.button').click(function() {    
        if (this.id == "add") {    
            $('#animTarget').addClass("myClass", "fast")    
        } else if (this.id == "toggle") {    
            $('#animTarget').toggleClass("myClass", 1000, "easeOutSine")    
        } else if (this.id == "switch") {    
            $("#animTarget").switchClass("myClass", "switchclass", "fast")    
        } else {    
            $('#animTarget').removeClass("myClass", "fast")    
        }    
    })    
});

Learn more here: How To Work With jQuery UI Effects

Question 38: What is the usage of Draggable, Droppable, Resizable, Selectable in jQuery UI?

There are only 5 plugins available in the interaction section; that is Draggable, Droppable, Resizable, Selectable and Sortable. Interaction Plugins handles complex behaviors such as drag and drop, resizing, selection and sorting.

Graphical representation of jQuery UI subordinates:

Draggable: It enables draggable functionality on any DOM element. Move the draggable object by clicking on it with the mouse and dragging it anywhere within the viewport.

Droppable: It enables any DOM element to be droppable, a target for draggable elements.

Resizable: It enables any DOM element to be resizable. With the cursor, grab the right or bottom border and drag to the desired width or height.

Selectable: It enables a DOM element (or group of elements) to be selectable. Draw a box with your cursor to select items. Hold down the Ctrl key to make multiple non-adjacent selections.

Sortable: It enables a group of DOM elements to be sortable. Click on and drag an element to a new spot within the list, and the other items will adjust to fit. By default, sortable items share draggable properties.

Learn more here: jQuery UI: Interaction Plugins

Question 39: What is the history of jQuery UI and how to use it?

jQuery UI is really very easy to learn and it provides abstractions for low-level interaction and animation, advanced effects and high-level, theme-able widgets, built on top of the jQuery JavaScript Library which you can use to build highly interactive web applications. The whole jQuery UI is categorized into four groups; they are core, interactions, widgets and effects.

The components of jQuery UI are: 

  • Core: It's a perquisite for other widgets and effects to work properly.
  • Interactions: It allows us to add behavior like Draggable, Droppable, Sortable, etc on the UI elements.
  • Widgets: It provides UI controls like tabs, dialog, slider, etc.
  • Effects: It provides ready to use effects like clip, bounce, explode, etc.

Learn more here: Introduction to jQuery U

Question 40: What $(document).ready(function()) is and when to use it?

$(document).ready(function()) is a jQuery event that fires as soon as the DOM is fully loaded and ready to be manipulated by script. This is the earliest point in the page load process where the script can safely access elements in the page's HTML DOM. This event is fired before all the images and CSS are fully loaded.

Learn more here: Basics of jQuery: Part 1

Question 41: Define jQuery UI Autocomplete ?

Autocomplete is one of the best widgets ON websites and is used in nearly all websites. jQuery has a powerful widget, autocomplete, and in this article I will try to explain how to use jQuery Autocomplete in websites. All the way and all other features of autocomplete. We can make autocomplete, using AJAX, to call to build a list (server-side) and then bind that list into a text box using JavaScript. However there are other alternatives to make autocomplete rather then this in an easy way. The most robust and efficient tool of autocomplete is jQuery-ui autocomplete and this tool is free and there is no need to license it.

Points to remember

  • The Autocomplete widget requires some functional CSS, otherwise it won't work. If you build a custom theme, use the widget's specific CSS as a starting point.
  • This widget manipulates its element's value programmatically, therefore a native change event may not be fired when the element's value changes.

Learn more here: jQuery UI Autocomplete

Question 42: What is jQuery UI Sortable and how to use it?

The jQuery UI is a library provided by jQuery for a better user interface. Using sortable we can reorder the DOM elements in the defined area. Users have to click on the item and drag that item to a new place. The other items will be automatically arranged. Accordingly, use the following procedure to enable sortable elements:

  1. Include the jQuery js file.
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.10.0.min.js"></script> 
  2. Include the jQuery UI js file.
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.3/jquery-ui.min.js" type="text/javascript"></script>  

     

Learn more here: jQuery UI Sortable

Question 43: Why to use jQuery $ sign?

The basic operation in jQuery is selecting an element in DOM. This is done with the help of $() construct with a string parameter containing any CSS selector expression. $() will return zero or more DOM elements on which we can apply an effect or a style.

Learn more here: Selectors in jQuery

Question 44: What is slice() method in jQuery?

This method selects a subset of the matched elements by giving a range of indices. In other words, it gives the set of DOM elements on the basis of it's parameter (start, end).

Syntax: .slice( start, end[Optional] )

Start: This is the first and mandatory parameter of the slice method. This specifies from where to start to select the elements.

End: This is an optional parameter. It specifies the range of the selection. This indicates where to stop the selection of elements, excluding end element.

Note: The Negative Indices started from -1. This last element is denoted by index -1 and so on. 

Learn more here: .slice() Method in jQuery

Question 45: What is jQuery Effects - Fading?

The fade methods define visibility of content in UI, in other words how the web page is hidden/shown. To use the fade methods of jQuery I need a jQuery library in my project, so I directly used the Google AJAX Libraries content delivery network to serve jQuery from Google. Doing so has several advantages over hosting jQuery on our server, decreased latency, increased parallelism, and better caching. We add the script to our project.

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> 

Our UI design is ready so now implement the fade methods. Here are the four types of jQuery fade methods: 

  1. fadeIn()
  2. fadeOut()
  3. fadeToggle()
  4. fadeTo()

Learn more here: jQuery Effects Using Fade Methods

Question 46: How to work with jQuery css() method?

The following code is very simple, no styles are applied. Now, we want to achieve the following style by using jQuery and some CSS.

 

Learn more here:  JQuery and CSS Selectors: Part 2

Question 47: What is queue() in Jquery? Use of queue() in jquery?

Delay comes under the custom effect category in jQuery. Its sole use is to delay the execution of subsequent items in the execution queue.

delay( duration [, queueName ] )

queueName is a name of the queue in which the delay time is to be inserted. By default it is a "fx" queue. A "fx" queue is also known as an effects queue.

Learn more here: Timers in jQuery: Delay Method

Question 48: How jQuery selectors are executed?

A selector starts with $(). In the parentheses may be an element, a class or an ID. For example:

<div class=”leftBorder”> C# Corner</div> 
 <div ID=”leftPanel”>C# Corner</div> 

For the preceding code, jQuery syntax (for selectors ) will be:

$(“div”).action  
$(“.leftBorder”).action  
$(“#leftPanel”).action 

So here we used the following three things: HTML tag name, class name and ID name. There are jQuery selectors. The factory function $() is a synonym of the jQuery() function. 

Learn more here: jQuery Selectors Basics

Question 49: What are the advantages of Ajax?

Ajax stands for Asynchronous JavaScript and XML; in other words Ajax is the combination of various technologies such as JavaScript, CSS, XHTML, and DOM, etc.

AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the entire page.

We can also define Ajax is a combination of client side technologies that provides asynchronous communication between the user interface and the web server so that partial page rendering occurs instead of complete page post back.

Advantages of AJAX based application

  • Improved application performance by reducing the amount of data downloaded from the server.
  • Rich, responsive and Slick UI with no page flickers.
  • Eliminates frequent page refresh which usually happens in a typical request/response model (Everything is updated on fly).
  • Easy to implement as there are variety of AJAX implementations available around.
  • AJAX mechanism works behind the scene nothing much required from user perspective.
  • Works with all the web browsers.
  • Avoids the round trips to the server.
  • Rendering of webpage faster.
  • Decreases the consumption of server resources.
  • Response time of application is faster.
  • Rendering of data is dynamic.

Learn more here: Introduction to Ajax and Ajax Control Toolkit

Question 50: How can you use array with jQuery?

Arrays are zero indexed, ordered lists of values. They are really handy for storing a set of values of the same data type.

var names = [“Name1”,”Name2”] //Recommended

Both of the preceding approaches are kind of static declarations. Now let's do some dynamic programming with Arrays.

var namearray = [];  
namearray.push(“Name1”) //Index 0  
namearray.push(“Name2”) //Index 1  
namearray.push(“Name3”) //Index 2  

Here, .push() is a jQuery function used in conjunction with Arrays that adds an element at the end of the array. Items can be inserted by specifying the index as well, as follows:

namearray[0] = “Name1”;  
namearray[1] = “Name2”;  
namearray[2] = “Name3”;  

Now let’s print the values of the array:

Console.log(namearray);

The statement above will produce the output as [ "Name1", "Name2",”Name3”].

We can see that we just printed the array object but not the individual values, so to extract individual values the following statement can be executed:

Console.log(namearray[0]) //Name1;  
Console.log(namearray[1]) //Name2;  

How to print an array of values using a for loop in jQuery:

var myArray = ["Name1", "Name2", "Name3"];  
for (var i = 0; i < myArray.length; i = i + 1) {  
   console.log(myArray[i]);  
} 

How to print an array of values using $.each() in jQuery: 

$.each(myArray, function (index, value) {  
   console.log(index + ": " + value);  
}); 

For more details read this: Query Arrays

More Interview Questions


Similar Articles