-
What is jQuery? - A Javascript library that make things like DOM selection/manipulation, AJAX, and animation, easier
-
What programming language does jQuery use? - Javascript
-
Is jQuery code executed on the client side, or server side? - Client side
-
How do you install/use jQuery in a project? What is the minimum setup needed to start using jQuery? - script tag, linked to a jquery CDN or locally hosted file
-
How do you select all elements with the class of “selected” in jQuery?
javascript $('.selected');
-
Can jQuery be used to make an AJAX request? - Yes
-
Is there any difference between
body onload()
anddocument.ready()
function? -document.ready()
function is different from bodyonload()
function for 2 reasons. First, we can have more than one
document.ready()function in a page where we can have only one
body onloadfunction. Second,
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 -
What is a CDN? - 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
-
Difference between
$(this)
andthis
in jQuery? -this
and$(this)
refers to the same element. The only difference is the way they are used.this
is used in traditional sense, whenthis
is wrapped in$()
then it becomes a jQuery object and you are able to use the power of jQuery -
What is the difference between
jquery.size()
andjquery.length
? -jQuery.size()
method returns number of element in the object. But it is not preferred to use thesize()
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 -
What is the difference between
$('div')
and$('<div/>')
in jQuery? -$('<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 -
What is the difference between
parent()
andparents()
methods in jQuery? - The basic difference is theparent()
function travels only one level in the DOM tree, whereparents()
function search through the whole DOM tree -
What is the difference between
eq()
andget()
methods in jQuery? -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 -
How do you implement animation functionality? - 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 - The syntax for a sample animated effect is the following: ```javascript $('#selector').animate({styles}, speed, easing, callback)
- styles: specifies one or more CSS properties/values to animate
- speed: 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
```
-
How to disable jQuery animation? - 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 -
How do you stop the currently-running animation? - Using jQuery
.stop()
method -
What is the difference between
.empty()
,.remove()
and.detach()
methods in jQuery? - 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 whereremove()
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 -
Explain
.bind()
vs.live()
vs.delegate()
vs.on()
- 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 withbind()
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 ofbind()
. 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 -
What is wrong with this code line?
javascript $('#myid.3').text('blah blah!!!');
- 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:javascript $('#myid\\.3').text('blah blah!!!');
-
How to create clone of any object using jQuery? - 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 nodesjavascript // Sample clone function $(document).ready(function() { $('#btnClone').click(function() { $('#dvText').clone().appendTo('body'); return false; }); });
-
Does events are also copied when you clone any element in jQuery? - As explained in previous question, using
clone()
method, we can create clone of any element but the default implementation of theclone()
method doesn't copy events unless you tell theclone()
method to copy the events. Theclone()
method takes a parameter, if you pass true then it will copy the events as welljavascript // Sample code $(document).ready(function() { $('#btnClone').bind('click', function() { $('#dvClickMe').clone(true).appendTo('body'); }); });
-
What is difference between
.prop()
and.attr()
? -.attr()
: Get the value of an attribute for the first element in the set of matched elements -.prop()
: 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 useprop()
to get values of elements which is modified via javascript/jquery , as it gives you the original value of an element's current state -
What is
event.PreventDefault()
? - Theevent.preventDefault()
method stops the default action of an element from happening. For example, prevents a link from following the URL -
What is the difference between
event.PreventDefault()
andevent.stopPropagation()
? -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 -
What is the difference between
event.PreventDefault()
andreturn false
? -e.preventDefault()
will prevent the default event from occurring,e.stopPropagation()
will prevent the event from bubbling up andreturn false
will do both -
What is the difference between
event.stopPropagation()
andevent.stopImmediatePropagation()
? -event.stopPropagation()
allows other handlers on the same element to be executed -event.stopImmediatePropagation()
prevents every event from running. Example for this method is as followedjavascript $('p').click(function(event) { event.stopImmediatePropagation(); }); $('p').click(function(event) { // This function won't be executed $(this).css("background", "red"); });
- Ifevent.stopPropagation()
was used in previous example, then the next click event onp
element which changes the css will fire, but in caseevent.stopImmediatePropagation()
, the nextp
click event will not fire -
How to check if number is numeric while using jQuery? - Using
isNumeric()
function -
How to check data type of any variable in jQuery? - Using
$.type(Object)
which returns the built-in Javascript type for the object -
How do you attach a event to element which should be executed only once? - 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 oncejavascript // Sample code $(document).ready(function() { $('#btnDummy').one('click', function() { alert('This will be displayed only onece'); }); });
-
Is it possible to hold or delay
document.ready
execution for sometime? - Yes, it's possible. A new methodjQuery.holdReady(hold)
was introduced to do this. This method allows to delay the execution ofdocument.ready()
eventdocument.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 referencedjavascript // Sample code $.holdReady(true); $.getScript("myplugin.js", function() { $.holdReady(false); });
-
What is chaining in jQuery? - 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 ```javascript // Sample code /* BEFORE CHAINING */
$(document).ready(function() { $ ('#dvContent').addClass('dummy');$('#dvContent').css('color', 'red'); $ ('#dvContent').fadeIn('slow'); });
/* AFTER CHAINING */
$(document).ready(function() {
$('#dvContent').addClass('dummy').css('color','red').fadeIn('slow');
});
```
-
How does caching helps and how to use caching in jQuery? - 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
javascript // WITHOUT CACHING $("#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 bejavascript // WITH CACHING 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 -
What are various methods to make ajax request in jQuery? - 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 -
Is there any advantage of using
$.ajax()
for ajax call against$.get()
or$.post()
? - By using jQuerypost()
or jQueryget()
, 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 reasons 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) -
What are deferred and promise object in jQuery? - Deferred and promise help in handling asynchronous functions like Ajax
-
Can we execute/run multiple Ajax request simultaneously in jQuery? If yes, then how? - 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 -
What are source maps in jQuery? - 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
-
Is it possible to get value of multiple CSS properties in single statement? - Yes, it is posiible to do so by using the
.css()
multi-property getterjavascript // Sample code $('#sample').css({ 'width': '100px', 'height': '200px', 'backgroundColor': 'yellow' });
-
How do you stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements? - It can be done via calling
.stop([clearQueue ] [, jumpToEnd ])
method and by passing both the parameters as true -
What is finish method in jQuery? - The
.finish()
method stops all queued animations and places the element(s) in their final state -
What is the difference between calling
.stop(true,true)
and.finish()
? - 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 -
What is jQuery no conflict? - The
noConflict()
method releases the hold on the $ shortcut identifier, so that other scripts can use it. You can also create your own shortcut very easilyjavascript var XYZ = $.noConflict();
-
What is
$
in jQuery? - The$
represents the jQuery Function, and is actually a shorthand alias for jQuery. It is typically used as a selector (i.e. a function that returns a set of elements found in the DOM)