You are on page 1of 13

Module 1 [16MCA42] Advanced Web Programming

Module -1
Introduction to jQuery

• Introducing jQuery

• jQuery fundamentals

• Creating the wrapped element set

• Bringing pages to life with jQuery

• Understanding the browser event models

• The jQuery Event Model

• Sprucing up with animations and effects

Text book to be referred:


Bear bibeault, Yehuda katz: jQuery in Action. 3rd Edn, DreamTech India,2008

ROOPA.H.M, DeptofMCA, RNSIT Page 1


Module 1 [16MCA42] Advanced Web Programming

Introducing jQuery
1. What is jQuery ? List the core features of jQuery
jQuery is a fast and concise JavaScript Library created by John Resig in 2006 with a nice
motto: Write less, do more. jQuery is a JavaScript toolkit designed to simplify various tasks by
writing less code. Here is the list of important core features supported by jQuery −
• DOM manipulation − The jQuery made it easy to select DOM elements, negotiate them and
modifying their content by using cross-browser open source selector engine called Sizzle.
• Event handling − The jQuery offers an elegant way to capture a wide variety of events, such
as a user clicking on a link, without the need to clutter the HTML code itself with event
handlers.
• AJAX Support − The jQuery helps you a lot to develop a responsive and feature rich site
using AJAX technology.
• Animations − The jQuery comes with plenty of built-in animation effects which you can use
in your websites.
• Lightweight − The jQuery is very lightweight library - about 19KB in size.
• Cross Browser Support − The jQuery has cross-browser support, and works well in IE 6.0+,
FF 2.0+, Safari 3.0+, Chrome and Opera 9.0+
• Latest Technology − The jQuery supports CSS3 selectors and basic XPath syntax.

2. With a neat diagram, discuss the steps performed by browsers before the document-
ready handler is executed
Before executing any script to apply the rich behaviours (dynamic behaviours). It is better to
wait until the document structure is fully parsed and the browser has converted the HTML
into its resulting DOM tree Accomplishing this in a older browsers is somewhat difficult, but
jQuery provides a simple means to trigger the execution of code once the DOM tree has
loaded (without waiting for external resources).
The formal syntax to do this is as follows:

jQuery(document). ready (function( ) {

// Your code goes here...

});

• First, wrap the document object using the jQuery( ) function

• call the ready( ) method,

• passing a function to be executed when the document is ready to be manipulated. This means
that inside the function passed to ready( ) you can safely access all of the elements of your
page.

ROOPA.H.M, DeptofMCA, RNSIT Page 2


Module 1 [16MCA42] Advanced Web Programming

A schema of the mechanism described is shown in figure below:

By passing a function to jQuery( ) or its alias $(), it instruct the browser to wait until the
DOM has fully loaded before executing the code.
3. What are different types of selectors in jQuery. Explain with syntax and examples.

• The jQuery ( ) function and its alias $( ) returns a jQuery object containing a set of DOM
elements that match the given criteria.

• jQuery provides a robust selector syntax that can be used to easily specify sets of elements
elegantly and concisely.
Table: Some simple CSS selector examples

Different types of selectors used in jQuery for selecting DOM elements are as follows:

• Universal selector
• ID selector
• Class selector
• Element selector

ROOPA.H.M, DeptofMCA, RNSIT Page 3


Module 1 [16MCA42] Advanced Web Programming

1. The All (or Universal) selector

• The first selector available is the All (or Universal) selector, which is represented by an
asterisk (*). As the name suggests, it allows you to retrieve all of the DOM elements of a web
page, even the head element and its children. Consider the following HTML page:

<!DOCTYPE html>
<html>
<head>
<title>jQuery in Action, 3rd edition</title>
</head>
<body>
<p>I'm a paragraph</p>

<script src="jquery-3.3.1.min.js"></script>
<script>
var $allElements = $('*');
</script>

</body>
</html>

• To retrieve all the elements of the page you need to use the Universal selector and pass it
to the jQuery() function (or its alias $()) in a statement like the following:
var $allElements = $('*');

• When saving the result of a selection made with jQuery in a variable, a widely adopted
convention is to prepend or (less commonly) append a dollar sign to the name of the
variable. This indicates it is a jQuery object(jQuery collection).
2. The ID selector

• The ID selector is one of the most used selectors, not only in jQuery but also in plain
JavaScript.
• The ID selector is characterized by a sharp (#) sign prepended to the element’s ID.
• Ex:
If you have this paragraph in your page
<p id="description">jQuery in Action is a book about jQuery</p>
you can retrieve it using the ID selector and jQuery by writing
$('#description');

• When used with the ID selector, jQuery returns a collection of either zero or one DOM
element.
• In case you have more than one element on a page with the same ID, the library retrieves
only the first matched element encountered. Using the ID selector you’re able to quickly
retrieve one element in the DOM.

ROOPA.H.M, DeptofMCA, RNSIT Page 4


Module 1 [16MCA42] Advanced Web Programming

3. The Class selector

• The Class selector is used to retrieve elements by the CSS class names used.

• jQuery follows the CSS conventions, so you have to prepend a dot before the chosen class
name.

• For example, if we have the following HTML code inside the <body> of a page

<div>
<h1 class="green">A title</h1>
<p class="description">I'm a paragraph</p>
</div>

<div>
<h1 class="green">Another title</h1>
<p class="description blue">I'm yet another paragraph</p>
</div>

and want to select the elements that have the class description, we need to pass
.description to the $( ) function by writing the following statement:
var $descriptions = $('.description');

• The result of this statement is an object, containing the two paragraphs of the HTML
snippet.

• In jQuery, like in CSS, it’s also possible to combine more class name selectors. If you want
to select all the elements having the classes description and blue, you can concatenate them,
resulting in $('.description.blue').

4. The Element selector

• The Element selector allows to pick up elements based on their tag name.

• Because of its support in almost any browser, jQuery uses getElementsByTagName() to


select elements by tag name behind the scenes.

• Ex: let’s say we want all the <div>s in a page. To achieve this task, we have to write
var $divs = $('div');

• It’s common to use it in conjunction with other selectors because usually lot of elements of
the same type in the pages. In such cases, it must be written before the other selectors.
Hence, if we want all <div>s having class clearfix, the following statement does the task:
var $clearfixDivs = $('div.clearfix');

• To select all the <div>s and the <span>s in a page, you can write
$('div, span');

ROOPA.H.M, DeptofMCA, RNSIT Page 5


Module 1 [16MCA42] Advanced Web Programming

4. Discuss selecting of elements using attributes in jQuery with examples.

• Attribute selectors are extremely powerful and allows to select elements based on their
attributes.

• These selectors are easily recognized because they’re wrapped with square brackets.

• For example, let’s take the following code:

<ul>
<li>
<a href="http://jquery.com">jQuery supports</a>
<ul>
<li><a href="css1">CSS1</a></li>
<li><a href="css2">CSS2</a></li>
<li><a href="css3">CSS3</a></li>
<li>Basic XPath</li>
</ul>
</li>
</ul>

Selector Description

$("a[href^='http://']") This matches all links with an href value beginning


with the exact string http://. The caret character (^)
is used to specify that the match has to occur at
the beginning of a value.

$("a[href!='http://jquery.com']") This matches all links, but not with an href which
has the value “jquery.com”.

form[method] This matches any <form> that has an explicit


method attribute.

input[type='text'] This selector matches all input elements with a


type of text.

div[title^='my'] This selects all div elements with a title attribute


whose value begins with my.

a[href$='.pdf'] This selects all links that reference PDF files.

a[href*='jquery.com'] This selector matches all <a> elements whose


attribute contains jquery.com anywhere in the
attribute value

div[class|='main'] This selector will find all the <div>s having


class="main" or having a class name starting with
main-, like class="main-footer".

span[data-technologies~="javascript"] This selects <span>s having an attribute like data-


technologies="javascript" but also data-
technologies="jquery javascript qunit".

ROOPA.H.M, DeptofMCA, RNSIT Page 6


Module 1 [16MCA42] Advanced Web Programming

input[type="text"][required] This selector retrieves all the <input>s that are


required and are of type text.

5. Implement DOM Manipulation methods for the following:


i. add( )
ii. get( )
iii. map( )

i. add( ): ADDING MORE ELEMENTS TO A SET


• This method allows to add more elements to an existing jQuery collection. This capability is
more useful when you want to add more elements after applying some method to the
original set.

• Let’s say that we want to match all <img>s that have either an alt or a title attribute. This
can be done as follows:
$('img[alt]').add('img[title]');

• Using the add( ) method in this fashion allows you to chain a bunch of selectors together,
creating a union of the elements that satisfy either of the selectors.

• add( ) are also significant within jQuery method chains because they don’t spoil the
original set but create a new set with the result.

• This is the syntax of the add ( ) method:


add(selector[, context])

• The add( ) method allow you to add existing elements to the set, but can also use it to add
new elements by passing it a string containing HTML markup.
Ex: $('p').add('<div>Hi there!</div>');
This fragment creates a set of all p elements in the document and then creates a new set
that includes the <div> created on the fly.
ii. get( ): FETCHING ELEMENTS BY INDEX

• jQuery allows you to treat a jQuery collection as a JavaScript array, it can use get( ) method
to obtain any element in the list by position.

• jQuery defines it as follows:

ROOPA.H.M, DeptofMCA, RNSIT Page 7


Module 1 [16MCA42] Advanced Web Programming

• For example, to obtain the first element in the set of all <img>s with an alt attribute on the
page, you could write
var imgElement = $('img[alt]').get(0);

• The get( ) method also accepts a negative index. Using get(-1) will retrieve the last element
in the set, get(-2) the second to last, and so on.

• In addition to obtaining a single element, get( ) can also return an array of all the elements of
the set if used without a parameter.

iii. map( ): TRANSLATING ELEMENTS OF A SET

• Often, we want to perform transformations on the elements of a set. For example, we may
want to collect all the IDs of the elements in the set or perhaps collect the values of a set of
form elements. The map( ) method comes in handy for such occasions.

• The following code will collect all the IDs of all the <div>s on the page:
var $allIDs = $('div').map(function( ) {
return this.id;
} );

6.Write jQuery program to Limit character input in the textarea including count.

ROOPA.H.M, DeptofMCA, RNSIT Page 8


Module 1 [16MCA42] Advanced Web Programming

<html>
<head>
<meta charset="utf-8">
<title>Limit character input in the textarea including
count</title>
<style type="text/css">
textarea {
display:block;
margin:1em 0;
}
</style>
</head>
<body>
<form>
<label>Maximum 15 characters</label>
<textarea id="textarea" maxlength="15"></textarea>
<span id="rchars">15</span> Character(s) Remaining
</form>
<script src="jquery-3.3.1.js"></script>
<script>
maxLength = 15;
$('textarea').keyup(function() {
var textlen = maxLength-$(this).val().length;
$('#rchars').text(textlen);
});
</script>
</body>
</html>

7. Write jQuery program to disable/enable the form submit button, based on check box.

<html>
<head>

<meta charset="utf-8">
<title>Disable/enable the form submit button</title>
</head>

<body>
<form action="lab1.html">
<input id="accept" name="accept" type="checkbox" value="y"/>I
accept<br>
<input id="submitbtn" name="Submit" type="submit" value="Submit" />
</form>

<script src="jquery-3.3.1.js"></script>

<script>
$("#accept").click(function() {
$("#submitbtn").attr("disabled", !this.checked);
});

ROOPA.H.M, DeptofMCA, RNSIT Page 9


Module 1 [16MCA42] Advanced Web Programming

</script>

</body>
</html>

8. Which are different sets of effect types that jQuery provides for animating the display
There are three sets of effect types:
• Show and hide
• Fade in and fade out
• Slide down and slide up

Showing and hiding elements gradually:

• The show(), hide(), and toggle() methods are more flexible ,When called with no
arguments, these methods effect a simple manipulation of the display state of the DOM
elements, causing them to instantaneously be revealed or hidden.

• But when arguments are passed to them, these effects can be animated so that the
changes in display status of the affected elements take place over a period of time.

• The full syntaxes of these commands.


hide(speed,callback)
show(speed,callback)
toggle(speed,callback)

— speed (Number|String) Optionally specifies the duration of the effect as a number of


milliseconds or as one of the predefined strings: slow, normal, or fast. If omitted, no
animation takes place, and the elements are immediately removed from the display.
— callback (Function) An optional function invoked when the animation completes. No
parameters are passed to this function, but the function context ( this) is set to the
element that was animated.
Fading elements into and out of existence:

• fadeIn() and fadeOut() affect the opacity of the elements.


fadeOut(speed,callback)
fadeIn(speed,callback)

— speed (Number|String) Specifies the duration of the effect as a number of milliseconds or


as one of the predefined strings: slow, normal, or fast. If omitted, the default is normal.
— callback (Function) An optional function invoked when the animation ompletes. No
parameters are passed to this function, but the function context (this) is set to the
element that was animated.

ROOPA.H.M, DeptofMCA, RNSIT Page 10


Module 1 [16MCA42] Advanced Web Programming

fadeTo(speed,opacity,callback)
— speed (Number|String) Specifies the duration of the effect as a number of milliseconds or
as one of the predefined strings: slow, normal, or fast. If omitted, the default is normal.
— opacity (Number) The target opacity to which the elements will be adjusted specified as a
value from 0.0 to 1.0.
— callback (Function) An optional function invoked when the animation completes. No
parameters are passed to this function, but the function context (this) is set to the
element that was animated.
Sliding elements up and down:

• Another set of effects that hide or show elements—slideDown( ) and slideUp( )—also works in
a similar manner to the hide( ) and show( ) effects, except that the elements appear to slide
down from their tops when being revealed and to slide up into their tops when being hidden.
slideDown(speed,callback)
slideUp(speed,callback)
— speed (Number|String) Specifies the duration of the effect as a number of milliseconds or
as one of the predefined strings: slow, normal, or fast. If omitted, the default is normal.
— callback (Function) An optional function invoked when the animation completes. No
parameters are passed to this function, but the function context (this) is set to the
element that was animated.

slideToggle(speed,callback)

• Performs slideDown () on any hidden wrapped elements and slideUp( ) on any non-hidden
wrapped elements. See the syntax description of these commands for their respective
semantics.

• Parameters
— speed (Number|String) Optionally specifies the duration of the effect as a number of
milliseconds or as one of the predefined strings: slow, normal, or fast. If omitted, no
animation takes place.
— callback (Function) An optional function invoked when the animation completes. No
parameters are passed to this function, but the function context (this) is set to the
element that was animated state of elements.
9. Listout the features of jQuery Event Model

• Provides a unified method for establishing event handlers.

• Allows multiple handlers for each event type on each element.

• Uses standard event-type names: for example, click or mouseover

• Passes the Event instance as the first argument of the handlers

• Normalizes the Event instance for the most-often-used properties

ROOPA.H.M, DeptofMCA, RNSIT Page 11


Module 1 [16MCA42] Advanced Web Programming

• Provides unified methods for event cancelling and default action blocking
10. How to attach event handlers to DOM elements in jQuery. Explain with syntax and
examples.

• Using the jQuery Event Model, we can attach event handlers to DOM elements with the
on( ) method.

• one of the advantages of using jQuery is that you can use its powerful jQuery( ) method to
retrieve a set of elements and then attach the same handler to all of them in one
statement.

• Consider the following simple example:


$('img').on('click', function(event) {
alert('Hi there!');
} );
This statement binds the supplied inline anonymous function as the click event handler for
every image on a page.
The full syntax of the on( ) method is as follows.

ROOPA.H.M, DeptofMCA, RNSIT Page 12


Module 1 [16MCA42] Advanced Web Programming

How to use jQuery?


There are two ways to use jQuery.
• Local Installation − You can download jQuery library on your local machine and include it
in your HTML code.
• CDN Based Version − You can include jQuery library into your HTML code directly from
Content Delivery Network (CDN).
Local Installation
• Go to the https://jquery.com/download/ to download the latest version available.
• Now put downloaded jquery-2.1.3.min.js file in a directory of your website, e.g. /jquery.

<head>
<script src="jquery-3.3.1.min.js"></script>
</head>

CDN Based Version


You can include jQuery library into your HTML code directly from Content Delivery
Network (CDN). Google and Microsoft provides content deliver for the latest version.

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
(OR)
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
</head>

ROOPA.H.M, DeptofMCA, RNSIT Page 13

You might also like