JQuery Questions
What is method chaining in jQuery? Provide an example.
What advantages does it offer?
Method chaining is a feature of jQuery that allows several
methods to be executed on a jQuery selection in sequence in a single code
statement. For example, the following snippets of code are equivalent:
Without chaining:
$( "button#play-movie" ).on( "click", playMovie );
$( "button#play-movie" ).css( "background-color", "orange" );
$( "button#play-movie" ).show();
With chaining:
$( "button#play-movie" ).on( "click", playMovie )
.css( "background-color", "orange" )
.show();
Notice that with chaining, the button
only needs to be selected one time, whereas without chaining, jQuery must
search the whole DOM and find the button before each method is applied. Thus,
in addition to yielding more concise code, method chaining in jQuery offers a
potentially powerful performance advantage.
Given the following HTML:
<div id="expander"></div>
and the following CSS:
div#expander{
width: 100px;
height: 100px;
background-color: blue;
}
Write code in jQuery to animate the
#expander
div, expanding it from 100 x 100 pixels to 200 x 200 pixels
over the course of three seconds.
This could be done in jQuery as follows:
$( "
#expander" )
.animate(
{
width: "200px",
height: "200px",
},
3000 );
What is the difference between
jQuery.get()
and jQuery.ajax()
?jQuery.ajax()
is the all-encompassing Ajax request method provided by
jQuery. It allows for the creation of highly-customized Ajax requests, with
options for how long to wait for a response, how to handle a failure, whether
the request is blocking (synchronous) or non-blocking (asynchronous), what
format to request for the response, and many more options.jQuery.get()
is a shortcut method that uses jQuery.ajax()
under the hood, to create an Ajax request that is typical
for simple retrieval of information. Other pre-built Ajax requests are provided
by jQuery, such as jQuery.post()
, jQuery.getScript()
, and jQuery.getJSON()
What selector would I use to query for
all elements with an ID that ends with
a particular string? Also, how would I modify the selector to retrieve only
<div>
elements whose IDs end with that same string?
Provide an example
Let’s say you want to retrieve all elements whose IDs end
with “txtTitle”. This could be done using the following selector:
$("[id$='txtTitle']")
To retrieve only
<div>
elements whose IDs end with “txtTitle”, the selector would
be:$("div[id$='txtTitle']")
Which of the two lines of code below is more efficient?
Explain your answer.
document.getElementById( "logo" );
or
$( "#logo" );
The first line of code, which is pure JavaScript without
jQuery, is more efficient and faster. Executing the second line of code, which
is jQuery, will trigger a call to the JavaScript version.
jQuery is built on top of JavaScript
and uses its methods under the hood to make DOM manipulation easier, at the
cost of some performance overhead. It is a good idea to remember that jQuery is
not always better than plain old JavaScript. Always consider whether using
jQuery really provides a useful advantage for your project.
Explain what the following code will do:
$( "div#first, div.first, ol#items > [name$='first']" )
This code performs a query to retrieve
any
<div>
element with the id first
, plus all <div>
elements with the class first
, plusall elements which are children of the <ol
id="items">
element and whose name
attribute ends with
the string "first"
. This is an example of using multiple selectors
at once. The function will return a jQuery object containing the results of the
query.
Explain what the following code does:
$( "div" ).css( "width", "300px" ).add( "p" ).css( "background-color", "blue" );
This code uses method chaining to
accomplish a couple of things. First, it selects all the
<div>
elements and changes
their CSS width to 300px. Then, it adds all the <p>
elements to the
current selection, so it can finally change the CSS background color for both
the <div>
and <p>
elements to blue.
What’s the deal with the
$
in jQuery? What is it and what does it mean?
Also, how can jQuery be used in
conjunction with another JavaScript library that also uses
$
for naming? Bonus credit if you can provide two answers.
Since
$
has no special meaning in JavaScript, it is free to be
used in object naming. In jQuery, it is simply used as an alias for the jQuery
object and jQuery()
function.
However, jQuery has no monopoly on
use of
$
, so you may encounter situations where you want to use it
in conjunction with another JS library that also uses $
,
which would therefore result in a naming conflict. jQuery provides the jQuery.noConflict()
method for just this reason. Calling this method makes it
necessary to use the underlying name jQuery
instead in subequent references to jQuery and its
functions.
Here’s an example from the jQuery documentation:
<script src="other_lib.js"></script>
<script src="jquery.js"></script>
<script>
$.noConflict();
// Code that uses other library's $ can follow here.
</script>
Alternatively, you can also use a closure instead of the
$.noConflict() method; e.g.:
(function ($) {
// Code in which we now exactly what the meaning of $ is
} (jQuery));
The code below is for an application that requires defining
a click handler for all buttons on the page, inlcuding those buttons that may
be added later dynamically.
What is wrong with this code, and how can it be fixed to
work properly even with buttons that are added later dynamically?
// define the click handler for all buttons
$( "button" ).bind( "click", function() {
alert( "Button Clicked!" )
});
/* ... some time later ... */
// dynamically add another button to the page
$( "html" ).append( "<button>Click Alert!</button>" );
The button that is added dynamically
after the call to
bind()
will not have the click handler attached. This
is because the bind()
method only attaches handlers to elements that exist at
the time the call to bind()
is made.
This problem is solved with functions
that use “event bubbling” to match events on both current and future elements.
In the past, this was done by replacing
bind()
with live()
. live()
was deprecated in jQuery 1.7 though. delegate()
works similarly to live()
but also provides control over how far an event must
bubble up the DOM.
However, the recommended method is to
use
on()
, which can behave like bind()
, live()
, or delegate()
depending on syntax. The following code attaches the
handler to all current and future buttons:// define the click handler
for all buttons
$( document ).on(
"click",
"button",
function() {
alert(
"Button Clicked!" )
});
/*
... some time later
... */
// dynamically add another button to the page
$(
"html" ).append(
"<button>Click Alert!</button>" );
Explain and contrast the usage of
event.preventDefault()
and event.stopPropagation()
.
Provide an example.event.stopPropagation()
stops an event from bubbling up the event chain, whereas event.preventDefault()
only precludes the browser’s default action on that event
from occurring, but the event still propogates up the event chain.
For example, consider the following code snippet:
// in this example, 'foo' is a div containing button 'bar'
$(
"#foo").click(
function() {
// mouse click on div 'foo'
});
$(
"#bar").click(
function(e) {
// mouse click on button 'bar'
e.stopPropagation();
});
Due to the call to
stopPropagation()
in the button’s click handler, the event never propogates
to the div so its click handler never fires. It effectively stops parent
elements from knowing about an event on their children.
In contrast, if you replaced the
above call to
stopPropagation()
with a call to preventDefault()
, only the browser’s default action would be precluded,
but the div’s click handler would still fire.
(Note: Although the
stopPropagation()
and preventDefault()
methods are mostly used in jQuery event handling
implementations, they apply to plain JavaScript as well.)
What is accomplished by returning false from (a) a jQuery event handler,
(b) a regular JavaScript onclick event handler for an anchor tag, and (c) a
regular JavaScript onclick event handler for a non-anchor tag (e.g., a div,
button, etc.)?
Hide answer
(a) Returning false from a jQuery event handler is effectively
the same as calling both preventDefault() and stopPropagation() on
the passed jQuery event object.
(b) Returning false from a regular JavaScript onclick event
handler for an anchor tag prevents the browser from navigating to the link
address and stops the event from propagating through the DOM.
(c) Returning false from a a regular JavaScript onclick event
handler for a non-anchor tag (e.g., a div, button, etc.) has absolutely no
effect.
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.
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.
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
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
·
26.
What is the use of jQuery filter?
·
The jQuery filter is used to filter
the certain values from the object list based on the criteria. Example is to
filter certain products from the master list of products in a cart website.
27. Which program is useful for
testing jQuery?
QUnit is used to test jQuery and it
is very easy and efficient.
28. What is CDN?
CDN is abbreviated as Content
Distribution network and it is said to be a group of companies in different
location with network containing copies of data files to maximize bandwidth in
accessing the data.
29. What are the two types of CDNs?
There are two types
of CDNs:
·
Microsoft – Load jQuery from Ajax CDN
·
Google – Load jQuery from Google libraries API
30. Which sign is used as a
shortcut for jQuery?
Dollar ($) sign is used as a shortcut
for jQuery.
31. Is jQuery is a client or
server scripting?
jQuery is a client scripting.
32. What is the script build up
by jQuery?
jQuery is a Javascript file and it is
single javascript file that contains common DOM, event effects and Ajax
functions.
34. What are all the ways to include jQuery in a page?
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
·
35.
What is the use of jQuery.ajax method ()?
·
jQuery.ajax method is used for
asynchronous HTTP requests.
36. Where can we download JQuery?
jQuery javascript
can be downloaded from jQuery official website – www.jquery.com
37. Is jQuery is a replacement of JavaScript?
No, jQuery is not a
replacement of JavaScript.
38. What is called chaining?
Chaining is used to
connect multiple events and functions in a selector.
39. What are the advantages of jQuery?
Following are the
advantages of jQuery:
·
Just a JavaScript enhancement
·
Coding is simple, clear, reusable
·
Removal of writing more complex conditions and loops
·
41.
What is the use of jQuery.data() method?
·
jQuery data method is used to
associate data with DOM nodes and JavaScript objects. This method will make a
code very concise and neat.
·
42. What is the difference between onload()
and document.ready()?
·
In a page, we can have only one
onload function but we can have more than one document.ready function.
Document.ready function is called when DOM is loaded but onload function is
called when DOM and images are loaded on the page.
·
43.
What is the use of jQuery each function?
·
jQuery each function is used to loop
through each and every element of the target jQuery object. It is also useful
for multi element DOM, looping arrays and object properties.
·
45.
Which is the fastest selector in jQuery?
·
ID and Element are the fastest
selectors in jQuery.
46. What is the slowest
selector in jQuery?
Class selectors are the slowest
selectors in jQuery.
47. Where jQuery code is
getting executed?
jQuery code is getting executed on a
client browser.
48. What is the method used to
define the specific character in place of $ sign?
‘NoConflict’ method is used to
reference a jQuery and save it in a variable. That variable can be used instead
of Sign.
49. Why jQuery is better than
JavaScript?
jQuery is a library used for
developing Ajax application and it helps to write the code clean and concise.
It also handles events, animation and Ajax support applications.
50. What are the types of selectors in jQuery?
There are three
types of selectors in jQuery:
·
CSS Selector
·
XPath Selector
·
Custom Selector