SlideShare une entreprise Scribd logo
1  sur  167
K.Srivatsan
•
•
•

IT Trainer Since 1991
Conducting Java Training Since 2004
About 40+ Corporate Clients
Agenda
1.
2.
3.
4.
5.
6.
7.
8.
9.

Introduction to jQuery
Selection and DOM Traversal
DOM and Attribute Manipulation
CSS Styling and jQuery
Event Handling with jQuery
Effects and Custom Animations
Ajax Calls with jQuery
jQuery UI
Plugin Development with jQuery
1

INTRODUCTION TO JQUERY
Topics
•

Motivation for jQuery

•

History Of jQuery

•

What is jQuery

•

jQuery vs Custom JavaScript

•

jQuery vs Other JavaScript Libraries

•

Quick Start jQuery
Motivation for jQuery
•

JavaScript has regained its prestige as rich internet applications and
Ajax gaining popularity

•

Rapid Application development is made possible by the use of
straightforward JavaScript , CSS and HTML.

•

Replace the cut-and-paste codes by full-featured JavaScript
libraries and also to solve difficult cross-browser problems

•

Improved patterns for web development.
– Lazy Initialization,Composite,Façade,Observer etc.,

•

jQuery-driven code is easier to write, simpler to read, and fasterto
execute than its plain JavaScript equivalent.
Unobtrusive JavaScript
•
•
•
•

Technique to have a clear separation of responsibilities
A web page with structure, style, and behavior each partitioned
Client-side code with the same level of care and respect as server-side
code
Extra work—But Not with JQuery.
What is jQuery
•

jQuery is a JavaScript library that simplifies:
–
–
–
–
–
–

•

HTML element selection and document object model (DOM) traversal
Element creation, deletion, and modification
Event handling
Animation
Ajax interactions
Custom widget integration (date picker, slider, dialogs, tabs, etc…) with
jQuery UI

jQuery is:
–
–
–
–
–

Free!
Open-source
lightweight footprint
Cross-browser compatible
Extensible! can write plugins or pick the one among a large list of
existing ones.
History of jQuery
•

The First Stable version of jQuery v1.0 was released in 2006 by a
team headed by John Resig

•

The Latest version of jquery 1.9 and 2.0 are announced

•

Can be downloaded from the http://jquery.com/download/

•

Minified Version :
– compressed version with whitespaces and comments stripped out,
shorter variable names in order to preserve bandwidth.
– Can use normal jquery.js version for Debugging purpose
Adding JQuery
•

Local System
– Can add using <script> by downloading the minified version
– <script type="text/javascript" src="path/to/jquery.min.js">

•

Adding Jquery with Google CDN
– http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
– http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js

•

To refer to the latest version of jQuery,
– http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js
Adding jQuery with Google CDN
•

Google has jQuery libraries on its Content delivery network and allows any
website to use it for free.

•

Caching: The most important benefit is caching. If any previously visited
site by user is using jQuery from Google CDN then the cached version will
be used. It will not be downloaded again.

•

Reduce Load: It reduces the load on web server as it downloads from
Google server's.

•

Serves fast : As Google has dozen's of different servers around the web
and it will download the jQuery from whichever server closer to the user.

•

Parellel Downloading: As the js file is on a separate domain, modern
browsers will download the script in parallel with scripts on your domain.
The jQuery Function
•

$() function returns a JavaScript object containing an array of the DOM
elements

•

Wraps the collected elements with extended functionality.

•

Return group of elements, which can be ready for another action.

•

To collect a group of elements, pass the selector to the jQuery function

•
•
•

$(selector)
Or
jQuery(selector)

•

$ is an alias for the jQuery() function
Document Ready Handler
•

The onload handler, executes statements after the entire page is fully
loaded.

•

This delays execution until after the DOM tree is created and all external
resources are fully loaded and the page is displayed in the browser window.

•

jQuery provides a simple means to trigger the execution of code once the
DOM tree has loaded and without waiting for external resources.
jQuery(document).ready(function() {
alert(jQuery('p').text());
});
$(function(){alert($ ('p').text());
});
First JQUERY-Anonymous Functions
<head>
<script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" >
$(document).ready(function() {
$("#msgId").html("<b>Hello From JQuery<b>");
});
</script>
</head>
<body>
<div id="msgId"></div>
</body>
JQuery with Named Functions
<script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" >
function setValue()
{
$("#msgId").html("Hello From JQuery")
}
$(function() {
$("#echoButton").click(setValue);
$("#echoButton").click(setValue());

});
</script>
<p id="msgId">Example</p>
<input type="button" value="Get TextFld Value" id="echoButton"/>
2

SELECTION AND DOM
TRAVERSAL
Topics
•
•
•
•
•
•
•
•
•
•

Basic Selectors
Hierarchy Selectors
Selection By Attribute
Form Selectors
Position Filters
Other Filters
Method Chaining
DOM Traversal
Filter Methods
Advanced Method Chaining
Basic Selectors
•

Basic jQuery selectors work the same as CSS selectors:

•

$(“*”) - // Selectors return a pseudo-array of jQuery elements

•

Selectors start with $(), representing the global jQuery function

•

It can take following arguments

•
•
•

Tag Name: Represents a tag name available in the DOM.
Tag ID:
Represents a tag available with the given ID in the DOM.
Tag Class : Represents a tag available with the given class in the DOM.

•

If more than one element has the same id only the first matched
element in the DOM will be returned
Basic Selectors
=$("#id1").text();
•

<p id="id1">Java</p>

•

<p id="id2" class="style1">JEE</p>

•

$(".style1").text();

<div>Spring</div>
=$(“div“).text();
Controlling the context
•

$(“”, $())

•

First argument -> is a selector,

•

Second argument -> denotes the context of the operation.

•

To Select the list Item inside a Division Identified with “colLef”

•

$("li", $(“#colLef")).css("border", "2px solid red");

-> function can have a second argument

Element to
Selection

Context of
Selection
Selection By Attribute
•

$('a[href]');
– Selects all <a> elements that have an href attribute.

•

$('a[href=“Welcome.html"]');
– Selects all <a> elements whose href attribute exactly matches
Welcome.html.

•

$(“div[id^=‘main’]”)
– Select all div elements Id starting with main

•

$(“div[id$=‘name’]”)
– Select all div elements Id END with name

•

$(“a[href*=‘msdn’]”)
– Select all href elements containing msdn
Working with DOM Attributes
•
•

jQuery can be used easily manipulate an element's attributes
Can be used to set and get a Attribute Value
– Get Attribute Value:

•
•
•
•

•

var title = $("em").attr("title");
$("#divid").text(title);
Set Attribute Value:
The attr(name, value) method can be used to set the named
attribute onto all elements in the wrapped set using the passed
value.
$("#myimg").attr("src", "/images/jquery.jpg");
Applying Styles
•

The addClass( classes ) method can be used to apply defined
style sheets onto all the matched elements. You can specify multiple
classes separated by space.

•

$("em").addClass("selected"); $("#myid").addClass("highlight");

•

attr( key, fn )Set a single property to a computed value, on all
matched elements.removeAttr( name )Remove an attribute from
each of the matched elements.hasClass( class )Returns true if the
specified class is present on at least one of the set of matched
elements.removeClass( class )Removes all or the specified
class(es) from the set of matched elements.
Hierarchy Selectors
•

$('#footer span');
– Selects the <span> elements that are descendants of the element with
the id footer.

•

$('ul > li');
– Selects the <li> elements that are immediate children of <ul> elements.

•

$('h2 + p');
– Selects the <p> elements that are immediately preceded by
an <h2> element.

•

$('h2 ~ p');
– Selects all <p> elements following an <h2> element that have the same
parent as the <h2>element.
Form Selectors
•
•
•
•
•

:input -> Input, textarea, select, and button elements
:enabled -> Form elements that are enabled
:disabled -> Form elements that are disabled
:checked -> Radio buttons or checkboxes that are checked
:selected -> Option elements that are selected

•

$(":checkbox")implies $("*:checkbox")).

•

var retVal =$("input:text#txtFld1").val();

•

var retVal=$("input:radio[name=rad]:checked").val();
Find Dropdown Selected Item
<select name=“cities”>
<select name=“cities”>
<option value=“1”>Chennai</option>
<option value=“1”>Chennai</option>
<option value=“2”>Trichy</option>
<option value=“2”>Trichy</option>
<option value=“3”>Madurai</option>
<option value=“3”>Madurai</option>
</select>
</select>

$(“select[name=‘cities’] option:selected”).val()
$(“select[name=‘cities’] option:selected”).val()
Selecting by Position
•

a:first
– This format of selector matches the first <a> element on the page.

•

p:odd
– This selector matches every odd paragraph element.

•

p:even
•

•

This selector matches every even paragraph element.

ul li:last-child
– chooses the last child of parent elements. In this example, the last <li>
child of each <ul> element is matched
Position Selection

•
•

Can filter the elements selected based on their position in the
collection
$('.article:eq(2)');
– Selects the third element with the class article.
– Elements in a collection are numbered starting with 0.

•

$('.article:gt(1)');
– From the collection of all elements with the class article, select all
elements following the second one.

•

$('.article:lt(3)');
– From the collection of all elements with the class article, select up to the
first three.
Other Selections
•

$(p:contains(‘java'));
– Selects all <p> elements that contain the string “java", either directly or
in any of the child elements.
– The text matching is case sensitive.

•

$('div:has(h2)');
– Selects all <div> elements that have at least one <h2> element as a
descendant.

•

$('option:not(:selected)');
– Selects all <option> elements that are not selected.

•

$('p:hidden'); , $('p:visible');
– Selects all <p> elements that are hidden/visible.
– An element is considered hidden if:
•
•
•
•

It has a CSS display value of none
It is a form element with type="hidden"
Its width and height are explicitly set to 0
An ancestor element is hidden, so the element is not shown on the page
jQuery Method Chaining
•

Selections return an instance of a jQuery object.

•

Returned instance can then invoke methods on the objects to
manipulate the HTML elements it represents.

•

Using this we can chain method calls on the object.

•

$('.status') .css('backgroundColor','yellow') .attr('title', 'Training by
Ramesh');
– This selects the elements with the class status, sets the background
color of the selected elements to yellow, and then sets the title attribute
of the selected elements.
Methods

•

find()
– From a set of selected elements to find descendants within the
context of the currently selected elements.

$s2=$(".style2");
$("#month_list1").find($s2).css("color","red");
•

each()
$("p").each(function(){
$(this).css("background-color","yellow");
});
$.each(names,function(i,val){
$("#msg2").append(val);
});
•

Methods
.filter()
– Constructs a new jQuery object from a subset of the matching elements.
– The supplied selector is tested against each element; all elements
matching the selector will be included in the result.

•

•

$("img").css("border","3px solid blue")
.filter(“.style2")
.css("border", "4px solid red");
find() vs Filters

• filter : reduces the set of already matched elements,
• find : gets descendants of the matched element
4

CSS STYLING AND JQUERY
Jquery Css
•

JQuery CSS selectors can be used to change CSS properties

•

CSS Methods do not modify the content of the jQuery object and
they are used to apply CSS properties on DOM elements.

•

The method for CSS manipulation is css()

•

selector.css( PropertyName, PropertyValue );

•

$("li").css("color", "red")
Css Manipulations
•
•

To Get the Current Css Style associated with an Element
$(“div”).css(“background-color”);

•

To Set a New style to an Element

•

$(“div”).css(“float”, “left”);

•
•

To Set Multiple style properties
$(“div”).css({

“color”:”blue”,
“padding”: “1em”
“margin-right”: “0”,
“marginLeft”: “10px”

}
•

);
Handling CSS Class
• To add and remove class
• $(“p”).removeClass(“blue”).addClass(“red”);
• To add if absent, remove otherwise
•
$(“div”).toggleClass(“main”);
• To test for class existance
•
if ($(“div”).hasClass(“main”)) { //… }
3

DOM AND ATTRIBUTE
MANIPULATION
Topics
•
•
•
•
•
•
•
•
•
•
•

DOM Traversal
Creating Elements
Inserting Elements
Inserting an Element Before or After Another Element
Inserting an Element as the First or Last Child of a Parent
Mass Insertion
Moving Elements
Cloning (Copying) Elements
Removing Elements
Replacing Elements
Element Content: HTML vs Text
DOM Traversal
•

DOM Traversal can be done using the results of a selection

•

Can select the children, the parents, and the siblings of each
element in the wrapped set.

•

$('h2').prev();
– Selects the set of elements that immediately precede <h2> elements.

•

$('h2').next('p');
– Selects the set of <p> elements that immediately follow <h2> elements.
– if the element immediately following an <h2> is not a<p>, it is not
included in the set of elements returned.
DOM Traversal
•

$('#form-button').siblings('fieldset');
– Gets all the siblings that are <fieldset>

•

$('.menu-li2').parent();
– Gets the parent elements of elements having the class menu-li2

•

$( "div" ).children().css( "border-bottom", "3px double red" );
– Get a set of elements containing all of the unique immediate children of
each of the matched set of elements.

•

$("li").closest("ul .style2").css("border","3px solid blue");
– Get a set of elements containing the closest parent element that
matches the specified selector, the starting element included.
Creating Elements
•

There are two ways to create elements in jQuery:

•

A string with HTML markup as argument to the jQuery function:
– $("<p>Hi there!</p>") : creates a New Paragraph

– var menuli1 = $('<li class="menu-li1">About Us</li>');

•

A string with HTML markup and a JavaScript object as the second
argument, can be text, event callbacks and other HTML attributes.
– var menuli1 = $('<li/>', { 'class': 'menu-li1', 'text': ‘About Us' });
Inserting Elements
•

Create elements can be insert elements into a page.

•

Elements can be inserted:
–
–
–
–

•

Before an existing element
After an existing element
Inside a container element, at its beginning
Inside a container element, at its end

Two approaches to each method of inserting elements into a page:
– Place the selected element(s) relative to another element
– Place an element relative to the selected element(s)
Inserting an Element Before Another Element
•

.insertBefore()
– $(‘<ol><li>Chennai</li></ol>').insertBefore('#place_list1');

•

.before()
– $("#place_list1 :eq(2)").before("<li>Orissa<li>");

•

.before():
– the selector expression preceding the method is the container before
which the content is inserted.

•

.insertBefore()
– the content precedes the method, either as a selector expression or
as markup created on the fly, and it is inserted before the target
container.
Inserting an Element as the Last Child of a Parent
•

.append() : As the Last Child
– newRow= "<tr><td>F105</td><td>jQuery</td></tr>";
• $("table").append(newRow);

•

.appendTo()

•

newRow =$("<li/>").html("Noida");
–

newRow.appendTo("#place_list1");
Cloning (Copying) Elements
•
•
•

Copy of element can be done with .clone() method ,
creates a “deep copy” of an existing selection.
All descendant elements and text are duplicated.

•

.clone() returns a jQuery object of the duplicate, leaving the original
selection in place.
var $article=$('.article:first').clone();
$('#section').append($article);
Removing Elements
•

There are two methods remove a selection: .detach() and.remove().
– both return the removed selection in case you want to restore it later.

•

Difference :
– .remove(), selection loses its associated jQuery data and its attached
events, which not a case with .detach().
– .detach() when you want to `reattach'' the selection to the page again in
the future;
– .remove() if you intend to discard the selection.
Deleting Elements
•
•

empty() : will remove all the contents of the selection.
remove() : will remove the selection and its contents.

•
•
•

<div>
<p><strong>foo</strong></p>
</div>

•

$('p').empty();

•

$('p').remove(); // --> "<div></div>"

// --> "<div><p></p></div>" //
Replacing Elements
•

To replace a selection : .replaceWith() and.replaceAll().

•

.replaceWith()
– Replace each element in the set of matched elements with the provided
new content
– returns the ones removed from the DOM.
• $("#place_list1 :eq(3)").replaceWith("<li>Madurai</li>");

•

.replaceAll()
– Replace each target element with the set of matched elements.
• $(“<div>Hello</div>”).replaceAll(“h1”);
5

EVENT HANDLING
Topics
•

Events Overview

•

Binding An Event Handler

•

Binding Shortcut Methods

•

Unbinding Handlers and “One-Shot” Handlers

•

The Event Object

•

Event Delegation

•

Event Delegation And jQuery

•

live() vs .delegate()
Event Handling
•
•
•

The event handling methods are core functions in jQuery.
Event handlers are method that are called when "something
happens" in HTML.
The term "triggered (or "fired") by an event" is often used.

•

.click( handler(eventObject) )

•

$("button").click(function(){
$("p").hide();
});

•

<p>This is a paragraph.</p>

•

<button>Click me</button>
JQuery Events
•

$(document).ready(function)
–

•

$(selector).click(function)
–

•

Triggers, or binds a function to the click event of selected elements

$(selector).focus(function)
–

•

Binds a function to the ready event of a document

Triggers, or binds a function to the focus event of selected elements

$(selector).mouseover(function)
–

Triggers, or binds a function to the mouseover event of selected
elements
Event Handling
function makeUpperCase()
{
$(this).val($(this).val().toUpperCase());
}
$(document).ready(function(){
$("#uppercase-field").keyup(makeUpperCase);
});

<input type="text" name="userName" id="uppercase-field">
Basic Syntax of Event Binding
• .bind( eventType [, eventData ], handler(eventObject) )
•

$(‘img’).bind(‘click’,function(event){alert(‘Message’;});

•

Bind can also take list of events
$('div').bind ('click keydown', function(e){
alert('event');
});

•

$(‘img’).bind(‘click’,imgclick(event));

• Allows unbinding the function
•

$(‘img’).unbind(‘click’,imgclick());
Bind multiple events simultaneously.
$("div.test").bind({
click: function(){
$(this).addClass("active");
},
mouseenter: function(){
$(this).addClass("inside");
},
mouseleave: function(){
$(this).removeClass("inside");
}
});
Many Events & Handler
•

Attaching a handler to multiple events

function handler(e){
alert('event');
}
$('div').click(handler)
.keydown(handler);
‘Event’ properties
•

event.target
– ref to element triggering event

•

event.target.id
– id of element triggering event

•

event.type
– type of event triggered

•

event.data
– second parm in the bind() func
Various mouse coordinate properties
Various keystroke related properties

•
•
Event Data
$("#img1").bind('click.ns1',{name: 'ramesh'},function(event){
if(event.data.name==='ram')
{
$("#img1").toggleClass("class1");
}
else
{
$("#img1").toggleClass("class2");
}
});
Event Name spacing
•

Can add a event within a specific namespace and then remove that
events from that namespace.
$("#img2").bind('click.ns2',mytoggler);
$("#btn1").click(function(){
$(“img").unbind("click.ns2");
});
$("#btn2").click(function(){
$("#img2").bind("click.ns2",mytoggler);
});
Event Bubbling
•

When an event is triggered on an element in the DOM tree

•

It handled by the event handler

•

It also checks with the parent of that element to see if it has
established a handler for the event type, and if so, it’s also invoked

•

Goes on up to the top of the DOM tree.

•

Because the event handling propagates upward like the bubbles ,is
termed event bubbling.
Event Handling Methods
•

preventDefault()
– Prevents any default semantic action from occurring.

•

stopPropagation()
– Stops any further propagation of the event up the DOM tree.
– Additional events on the current target aren’t affected.
– works with browser-defined events as well as custom events.

•

stopImmediatePropagation()
– Stops all further event propagation including additional events on the
current target.
Event Bubbling
$( 'h1,a' ).on( 'click', function( event ) {
event. stopPropagation();
alert( $( this ).attr( 'id' ) ); }
<h1 class="style1" id="hd1">
<a href="#1" id="anch">
<span id="sp">Using Events</span>
</a>
</h1>
.stopPropagation() on the event object — stop the propagation of
events up
Preventing the default action
•

preventDefault()
– Called on the event object, used to prevent the default action of an
event;

$( 'a' ).on( 'click', function( event ) {
event.preventDefault();
alert('I was just clicked!' );
});
Live() Method
•

jQuery can attach event handler to any future elements which
matches the original selector,

•

Live events do not bubble in the traditional manner and cannot be
stopped using stopPropagation or stopImmediatePropagation.

•

To remove a live event die() method is used

•
•
•
•

$('#listLive>li')
.live('mouseover', function(){ $(this).addClass('selected'); })
.live('mouseout', function(){ $(this).removeClass('selected'); });
});
die() Method
•

Remove all event handlers previously attached using .live() from the
elements

•

This method is analogous to calling .unbind() with no arguments,
function aClick() {
$("div").show().fadeOut("slow");
}
$("#bind").click(function () {
$("#theone").live("click", aClick).text("Can Click!");
});
$("#unbind").click(function () {
$("#theone").die("click", aClick).text("Does nothing...");
});
On Method
•

.on( events [, selector ] [, data ], handler(eventObject) )

•

Introduced with jQuery 1.7,

•

Its combination of bind, live method.

•

Bind
$( "#members li a" ).on( "click", function( e ) {} );
$( "#members li a" ).bind( "click", function( e ) {} );

•

Live
$( document ).on( "click", "#members li a", function( e ) {} );
$( "#members li a" ).live( "click", function( e ) {} );
On Method
$(function(){
$(document.body).on('mouseover',"#tab tr", function(){
$(this).addClass("selected");
}) .on('mouseout',"#tab tr", function(){$(this).removeClass("selected")});

$('#add').click(function(){
$('#tab').append('<tr><td>1</td><td>Jquery</td></tr>');
});

});
Triggering Events
•

trigger( eventType, data )
– Execute all handlers and behaviors attached to the matched elements
for the given event type.
– Data to be passed to the handlers as the second parameter (after the
event instance).

•
•
•

$("#button1").bind("click", (function () {
alert("Button 1 is clicked!");
}));

•

$("#button2").bind("click", (function () { alert("Button 2 is clicked!");
$("#button1").trigger("click"); }));
Creating Custom Events
•

Can Create our own custom events using jQuery event binder
Methods

•

Done by providing event binder method with a unique name for a
custom event.

•

Custom events are programmatically triggered using the jQuery
trigger() method.
Creating Custom Events
$(function(){
$("p").on("myCustomEvent", function(event,d){
alert("event"+ event.type + "data"+ d.name);
$(this).text(" I am triggered by Custom event !");
});
$("button").click(function (e ) {
var e = jQuery.Event( "myCustomEvent");
$("p").trigger(e,{name:'ram'});
});
});
ContextMenu - Event
•

The contextmenu event is fired when the right button of the mouse
is clicked before the context menu is displayed

•

Can use this Event with jQuery to Disable Right Click on a Page

$(document).bind('contextmenu',function(){
alert('right button disabled for security');
return false;
});
EFFECTS AND ANIMATIONS
Showing and hiding elements
•

Showing or hiding elements are simple and pop elements into
existence or make them instantly vanish!

•

show()
– to show the elements in a wrapped set, and hide() to hide them.

•

jQuery hides elements by changing their style.display properties to
none.

•

If an element in the wrapped set is already hidden, it will remain
hidden but still be returned for chaining.
Useful Functions
•
•
•
•

.hide()
– display:none
.show()
– display:true
.toggle(func1, func2)
– first click calls func1, next click executes func2
.hover(over, out)
– mouseover, mouseout
Useful Functions
•
•

.hide()
.show()
– $(“div”).show();
– $(“div”).show(“slow”);
– $(“div”).hide(“fast”);

•

.toggle(func1, func2)
– first click calls func1, next click executes func2

•

.hover(over, out)
– mouseover, mouseout
Fading Elements
•

fadeIn(speed,callback)
– Causes any matched elements that are hidden to be shown by
gradually changing their opacity to their natural value.
– This value is either the opacity originally applied to the element, or 100
percent.
– The duration of the change in opacity is determined by the speed
parameter.
– Only hidden elements are affected.
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeIn();
$("#div2").fadeIn("slow");
$("#div3").fadeIn(3000);
});
});
Fading Elements
•

fadeOut(speed,callback)
– Causes any matched elements that aren’t hidden to be removed from
the display by gradually changing their opacity to 0 percent and then
removing the element from the display.
– The duration of the change in opacity is determined by the speed
parameter.
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeIn();
$("#div2").fadeIn("slow");
$("#div3").fadeIn(3000);
});
});
Fading Elements
•

fadeTo(speed,opacity,callback)

•

Doesn’t remember the original opacity of an element.

•

Used to explicitly change the opacity to a specific value.
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeTo("slow",0.15);
$("#div2").fadeTo("slow",0.4);
$("#div3").fadeTo("slow",0.7);
});
});
Sliding Elements Up and down
•

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.

•

As with hide()and show(), the slide effects have a related method that will
toggle the elements between hidden and revealed: slideToggle().

•

slideDown(speed,callback)
– Causes any matched elements that are hidden to be shown by gradually
increasing their vertical size. Only hidden elements are affected.
slideUp(speed,callback)
– Causes any matched elements that are displayed to be removed from
the display by gradually decreasing their vertical size.

•
Sliding Elements
$(“div”).slideUp();
$(“div”).slideUp();
$(“div”).slideDown(“fast”);
$(“div”).slideDown(“fast”);
$(“div”).slideToggle(1000);
$(“div”).slideToggle(1000);
Reset Predefined Spees
– jQuery.fx.speeds.fast = 50;

•

Create a new pre-defined speed
– jQuery.fx.speeds.turtle = 3000;
Creating Custom Animation
•
•

•

Core Library has few effects, can use Pluggins to add special effects
The animate() wrapper method, allows us to apply custom animated effects
to the elements of a wrapped set.
The animate( ) method performs a custom animation with a set of CSS
properties.
Done gradually, animating the effect at the chosen speed:

•

selector.animate( params, [duration, easing, callback] );

•

params:

•

–

•

duration:
–

•

This is optional parameter representing how long the animation will run.

easing: ( linear and swing)
–

•

A map of CSS properties that the animation will move toward.

This is optional parameter representing which easing function to use for the transition

callback:
–

This is optional parameter representing a function to call once the animation is complete.
Animate
$("#out").click(function(){
$("#block").animate({
width: "70%",
opacity: 0.4,
marginLeft: "0.6in",
fontSize: "3em",
borderWidth: "10px"
}, 1500 );
});
Chaining Animation

$(“div”).animate({width: “90%”},100)
$(“div”).animate({width: “90%”},100)
.animate({opacity: 0.5},200)
.animate({opacity: 0.5},200)
.animate({borderWidth: “5px”});
.animate({borderWidth: “5px”});

By default animations are queued and than
performed one by one
Controlling Animations Sync
$(“div”)
$(“div”)
.animate({width: “90%”},
.animate({width: “90%”},
{queue:false, duration:1000})
{queue:false, duration:1000})
.animate({opacity : 0.5});
.animate({opacity : 0.5});

The first animation will be performed
immediately without queuing
Stopping Animations
•

stop(clearQueue,gotoEnd)
– Halts any animations that are currently in progress for the elements in
the matched set.

•

clearQueue (Boolean)
– If specified and set to true, not only stops the current animation,but any
other animations waiting in the animation queue.

•

gotoEnd (Boolean)
– If specified and set to true, advances the current animation to its logical
end (as opposed to merely stopping it).
JQUERY –AJAX INTERACTION
Ajax Interaction
XMLHttpRequest
•

JavaScript object

•

Adopted by modern browsers
– Mozilla™, Firefox, Safari, and Opera

•

Communicates with a server via standard HTTP GET/POST

•

XMLHttpRequest object works in the background for performing
asynchronous communication with the backend server
– Does not interrupt user operation
Server-Side AJAX Request Processing
•

Server programming model remains the same
– It receives standard HTTP GETs/POSTs
– Can use Servlet, JSP, JSF, ...

•

With minor constraints
– More frequent and finer-grained requests from client
– Response content type can be
•

text/xml

•

text/plain

•

text/json

•

text/javascript
Ajax with jQuery
•

$.get( url, [data], [callback], [datatype] )
– Load a remote page using an HTTP GET request.

•

$.getJSON( url, [data], [callback] ):
– Load JSON data using an HTTP GET request.

•

$.getScript( url, [callback] )
– Loads and executes a JavaScript file using an HTTP GET request

•

.$.post( url, [data], [callback], [type] )
– Load a remote page using an HTTP POST request.

•

$.load( url, [data], [callback] )
– Load HTML from a remote file and inject it into the DOM

•

$.ajax():
– To do something when XHR fails, or to specify options on the fly.
Load Method
•
•
•

•
•

•

This method is called on a selection ,
Fetches the HTML from a URL and uses the returned HTML to
populate the selected element.
In addition to URL optionally can provide a selector , jquery will
fetech only the matching content from the returned HTML
Load Method with Post Data
$("#disDiv").html(ld_img).load('Response.jsp',
{"name":name} );
Load Method with GET Data
– $("#disDiv").html(ld_img).load('Response.jsp', '&name='+name);
$.ajax()
•

Powerful and straightforward way of creating ajax request

•

It takes an configuration object that has the all instructions required

•

Has the ability to specify success and failure callback

•

Configuration object can be defined separately makes it easier to
write and reuse the code
Making an Ajax Call
$(document).ready(function(){
$("button").click(function(){
$.ajax({url:"First.Jsp", success:function(result){
$("div").html(result);
}});
});});
</script>
</head>
<body>
<div><h2>Let AJAX change this text</h2></div>
<button>Change Content</button>
</body>
</html>
Get and Post Method
•
•
•

$.get(“Sample.jsp", function(data) {
alert("Data Loaded: " + data);
});

•

jQuery.post( url [, data ] [, success(data, textStatus, jqXHR) ] [,
dataType ] )

•
•

To Post the Form Data
$.post(“Sample.jsp", { name: “Ramesh", age: "29" } );

•
•

To Post the Entire Form Data
$.post(“Sample.jsp", $("#frm").serialize());
$.ajax()
•

$.ajax() method. – Used to make Ajax Calls
var options = {

type: 'GET',
url: ‘ProcessData.jsp',
dataType: 'html',
error: function(xhr, textStatus, errorThrown) {
alert('An error occurred! ' + errorThrown);
},
success: function(data, textStatus) {
$('body').append( data );
}
};
$.ajax( options );
Load Java Script
Show.js
function show()
{
data =new Array("Head First Java","Spring in Action","thinking in Java");
}

var scriptUrl = "../js/Show.js";
$.getScript(scriptUrl,function(){
show();
$("#disDiv").html(data);
});
JQuery AJAX Events:
•
•
•
•

•
•
•

•

The methods used during the life cycle of AJAX call progress.
Based on different events/stages following methods are available:
ajaxComplete( callback )
Attach a function to be executed whenever an AJAX request completes.
ajaxStart( callback )
– Attach a function to be executed whenever an AJAX request begins and
there is none already active
.ajaxError( callback )
– Attach a function to be executed whenever an AJAX request fails.
ajaxSend( callback )
– Attach a function to be executed before an AJAX request is sent.
ajaxStop( callback )
– Attach a function to be executed whenever all AJAX requests have
ended
ajaxSuccess( callback )
– Attach a function to be executed whenever an AJAX request completes
successfully.
Ajax Global Events
•

Events that are broadcast to all elements in the DOM, triggering any
handlers which may be listening.
$("#loading").bind("ajaxSend", function(){
$(this).show(); })
.bind("ajaxComplete", function(){ $(this).hide();
});

•

Can be disabled for a particular Ajax request
$.ajax({
url: "test.html",
global: false,
});
Local Events
•

These are callbacks that you can subscribe to within the Ajax
request object
$.ajax({
beforeSend: function(){
},
complete: function(){
}
});
Deprecated Methods since 1.8
•

The jqXHR.success(), jqXHR.error(), jqXHR.complete() callbacks
are deprecated as of jQuery 1.8.

•

jqXHR.done(function(data, textStatus, jqXHR) {});
– An alternative construct to the success callback option,
the .done() method replaces the

•

jqXHR.fail(function(jqXHR, textStatus, errorThrown) {});
– An alternative construct to the error callback option

•

jqXHR.always(function(data|jqXHR, textStatus, jqXHR|
errorThrown) { });
– An alternative construct to the complete callback option
Example
var jqxhr = $.ajax( "example.jsp" ).done(function() {
alert("success"); })
.fail(function() { alert("error"); })
.always(function() { alert("complete"); });
JSON: JavaScript Object Notation.
•
•
•
•
•

Lightweight text-data interchange format
"self-describing" and easy to understand
Uses JavaScript syntax for describing data objects
JSON parsers and JSON libraries exists for many different
programming languages
JavaScript program can use the eval() to get native JS objects.

{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
The employees object is an array of 3 employee records (objects).
JSON Syntax Rules
•

JSON syntax is a subset of the JavaScript object notation syntax:
–
–
–
–

Data is in name/value pairs
Data is separated by commas
Curly braces hold objects
Square brackets hold arrays

•
•
•

JSON Name/Value Pairs
JSON data is written as name/value pairs.
A name/value pair consists of a field name (in double quotes),
followed by a colon, followed by a value:

•

"firstName" : "John“ equivalent to

firstName = "John"
Working With Json Data
•

Servers return JSON string against a request.

•

getJSON() parses the returned JSON string and makes the
resulting string available to the callback function

•

[selector].getJSON( URL, [data], [callback] );

•

data:
– An object whose properties serve as the name/value pairs used to
construct a query string to be appended to the URL, or a preformatted
and encoded query string.

•

Callback:
– The data value resulting from digesting the response body as a JSON
string is passed as the first parameter to this callback, and the status as
the second.
Generating JSON Data
User user = new User(101,”Ramesh);
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValue(new File(“user.json"), user);
System.out.println(mapper.writeValueAsString(user));
} catch (Exception e) {
e.printStackTrace();
}
Working With Json Data
$(document).ready(function() {
$("#driver").click(function(event){ $.getJSON('user.json', function(jd)
{
$('#id1').html('<p> Name: ' + jd.name + '</p>');
$('#id1').append('<p>Age : ' + jd.age+ '</p>');
});
});
});
<div id="id1" > </div>
<input type="button" id="driver" value="Load Data" />
Ajax with JSON Data
$.ajax({
type: "GET",
cache: false,
contentType: "application/json; charset=utf-8",
url: 'JsonResponse.jsp',
async: true,
success: function (data, textStatus, jqXHR) {
if (textStatus == "success") {
$("#disDiv").text(data);
}
},
error: function (jqXHR, textStatus, errorThrown) {
handleError(jqXHR);
}
});
}
JQUERY-UI
jQuery UI - Overview
•

Provides abstractions for low-level interaction and animation, advanced effects
and high-level, themeable widgets

•

Built on top of the jQuery JavaScript Library

•

Used to build highly interactive web applications

•

Javascript UI libraries:
o YUI - Yahoo! User Interface library
o

digit - Dojo User Interface library

o

Protoype UI
UI Library
•

Jquery has various Widgets using UI Libraries

•

Required Libraries are downloaded and added to the pages

•

CSS

•

<link rel="stylesheet" href="themes/base/jquery.ui.all.css">

•

JS Libraries
<script src="js/jquery-1.9.0.js"></script>
<script src="ui/jquery.ui.core.js"></script>
<script src="ui/jquery.ui.widget.js"></script>
<script src="ui/jquery.ui.resizable.js"></script>

Can add the Appropriate
.js files,for the required
UI Effects
UI Library Based Effects:
•

Call effect on any DOM element

•

.effect(effect,[options],[speed],[callback]}
o speed
 "slow", "normal", or "fast" or # of milliseconds
o callback
 function called after effect is completed

•

Blind : Blinds the element away or shows it by blinding it in

•

Explode :Explodes the element into multiple pieces.

•

Fold : Folds the element like a piece of paper.

•

Highlight : Highlights the background with a defined color.

•

Pulsate :Pulsates the opacity of the element multiple times

•

Scale : Shrink or grow an element by a percentage factor.

•

Shake :Shakes the element vertically or horizontally n-times.

•

Slide : Slides the element out of the viewport
UI Library Based Effects
•
•

<script src="../ui/jquery-ui.core.js"></script>
<script src="../ui/jquery-ui.js"></script>

•

$(function() {

•

$("#button").click(function() {

•
•
•
•
•

$("#effect").effect('blind',500,function(){
alert("Done");
});
});
});
Draggable
•

Make the selected elements draggable by mouse.

•

Can also drag& drop, Using Droppable plugin, which provides a
drop target for draggables.

•

Initialize the draggable with the addClasses option specified:

•

$( ".selector" ).draggable({ addClasses: false });

•

axisType: Constrains dragging to either the horizontal (x) or vertical
(y) axis. Possible values: "x", "y".

•

$( ".selector" ).draggable({ axis: “y" });
Draggable
$(function() {
$( "#draggable" ).draggable();
});
</script>
</head>
<body>
<div id="draggable" class="ui-widget-content">
<p>Using Drags</p>
</div>
Droppable
•

Makes selected elements droppable

•

They accept being dropped on by draggables.

•

Can specify which draggables each will accept.

•

$( "#draggable" ).draggable();

•

Can Initialize the droppable with the accept option specified:

•

$( ".selector" ).droppable({ accept: “#jsp " });
Droppable
$(function() {
$(".square").draggable();
$(".squaredotted").droppable({
drop : function(event, ui) {
$("#info").html("dropped!");
},
over : function(event, ui) {
$("#info").html("moving in!");
},
out : function(event, ui) {
$("#info").html("moving out!");
}
});
});
Droppable- Accept
$(".square").draggable();
$("#serverSideScript").droppable({
accept : "#jsp",
drop : function(event, ui) {
$(this).css("background-color", "lightgreen")
},
out : function(event, ui) {
$(this).css("background-color", "")
}
•

<div id="jsp" class="square">Jsp</div>

•

<div id="serverSideScript" class="squaredotted">Server Side Scripting
Language</div>
Resizeable
•

The jQuery UI Resizable plugin makes selected elements resizable

•

Has a draggable resize handles

•

Can be configured with one or more handles as well as min and
max width and height.

$(function() {
$( "#resizable" ).resizable(
minHeight:'140',minWidth:'100',
maxHeight:'300',maxWidth:'250'});
});
Buttons
•

Enhances standard form elements like buttons, inputs and anchors
to themeable buttons with appropriate hover and active styles.

•

$( ".selector" ).button({ disabled: true });

$( ".selector" ).button( {
icons: { primary: "ui-icon-gear",
secondary: "ui-icon-triangle-1-s"
}
});
$( ".selector" ).button({ label: "custom label" });
Date Picker
Date Picker
•

Used in textfield to pop up calendar.

•

Choosing day from calendar puts date string into textfield

•

HTML

•

<input type="text" id="date-field"/>

•

JavaScript

•

“datepicker()” called on the textfield
–

$("#date-field").datepicker();
Date Picker
<form action=#">
From: <input type="text"/>
Departure Date: <input type="text" id="start-date"/>
Return Date: <input type="text" id="end-date"/>
<input type="button" value="Show Flights"/>
<input type="button" value="Show Hotels"/>
</form>
$(function() {
$("#start-date").datepicker();
$("#end-date").datepicker({ changeMonth: true,
numberOfMonths: 2 });
});
Main Option of DatePicker
•

$(function() {
$("#bDate").datepicker({buttonImage: "../images/calendar.gif",
buttonImageOnly: true,showOn: "button"});
});

•

buttonImage :
– A URL of an image to use to display the datepicker when the showOn
option is set to "button" or "both".

•

buttonImageOnly:
• Just the button image only or inside a button element.
• Used if the buttonImage option has also been set.
Accordian
Accordion Panel

•

Horizontally stacked panels with wide tabs

•

HTML
– Need container to hold the tabs

•

Create alternating pairs of text with links and content
<h2><a href="#">Panel 1</a></h2>

<div>Content for Panel 1</div>
<h2><a href="#">Panel 2</a></h2>
<div>Content for Panel 2</div>

•
•

JavaScript
Call “accordion()” on the div container
$("#main-accordion-panel-div").accordion();
Accordian
<script>
$(document).ready(function() {
$(“#accrd ").accordion();
});
</script>
•

$("#accrd1").accordion({event :'mouseover'});
var icons = {
header: "ui-icon-circle-arrow-e",
activeHeader: "ui-icon-circle-arrow-s"
};

•

$("#accrd2").accordion({icons: icons});
Tab Panel
Tabbed Panel
•
•

Tabbed panel where clicking tabs changes content inside
Make a div container to hold the tabs
–

•
•

<div id="main-tabbed-panel-div">…</div>

Include a ul list containing internal hyperlinks
<ul>
<li><a href="#panel1">Go to Panel 1</a></li>
<li><a href="#panel2">Go to Panel 2</a></li>
</ul>

•

Call “tabs()” on the div container
$("#main-tabbed-panel-div").tabs();
Tab Panel
<script>
$(document).ready(function() {
$("#tabs").tabs();
});
</script>
<div id="tabs">
<ul>
<li><a href="#fragment-1"><span>One</span></a></li>
<li><a href="#fragment-2"><span>Two</span></a></li>
<li><a href="#fragment-3"><span>Three</span></a></li>
</ul>
<div id="fragment-1">
<p>First tab is active by default:</p>
<pre><code>This is the First Tab Panel</code></pre>
</div>
Tab- Options
•

collapsible (default: false)
– Click on selected tab to hide it
– $("#main-id").tabs({ collapsible: true });

•

disabled (default: empty array)
– An array of tab numbers (0-based) that should be disabled on startup

•

event (default: click)
– The type of event that should initiate tab selection
– $("#main-id").tabs({ event: "mouseover" });
AutoComplete
•

Autocomplete enables users to quickly find and select from a prepopulated list of values as they type, leveraging searching and
filtering.

•

The plugin starts searching for entries that match and displays a list
of values to choose from.

•

You can pull data in from a local or remote source:
$( "#tags" ).autocomplete({
source: availableTags
});
AutoComplete
$(function() {
var scripts= ["JavaScript“,"Lisp“,"Ruby“, "Scala“, "Scheme” ];
$( "#tags" ).autocomplete({source: scripts,select: function( event, ui ) {
alert("Item Selected"+ui.item.value); }
});

•

});

<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" />
</div>
Dialog
•
•

A way delivering information to the user.
Created by Selecting the content to become the body and the dialog()
method is applied.

•

dialog(options)
– Draggable,height,width,focus,show,title etc.,

•

dialog('disable')

•

dialog('open')
– Opens a closed dialog box.
$(function() {
$( "#dialog" ).dialog();

});
Dialog
•
•
•
•
•

$("#diaMsg").dialog({modal: false,buttons:{
Ok:function(){$(this).dialog("close");
$("#diaAnch1").hide();
$("#moreCourse").show();
}

•

Modal:
– If set to true, the dialog will have modal behavior;
– other items on the page will be disabled and cannot be interacted .

•

Buttons:
– Buttons that should be displayed on the dialog.
Creating Menu
•

Can create Menu with mouse and keyboard interactions for
navigation.

•

Created from any valid markup that has parent/child relationship
and each menu item has an anchor.
<ul id="menu">
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a>
<ul>
<li><a href="#">Item 2-1</a></li>
<li><a href="#">Item 2-2</a></li>
</ul>

</li>
<li><a href="#">Item 3</a></li>
</ul>
Menu
•

$( ".selector" ).menu({ disabled: true });

•

$( ".selector" ).menu({ icons: { submenu: "ui-icon-circle-trianglee" } });
Sliders
•

To make selected elements into sliders.

•

The handle can be moved with the mouse or the arrow keys.

$( "#slider-range" ).slider(
{
range: true,
min: 0,
max: 500,
values: [ 75, 300 ],
slide: function( event, ui ) {
$( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ]
);
} });
EXTENDING JQUERY
Plugin
•

A plug-in is piece of code written in a standard JavaScript file

•

Plugin works with a collection of elements

•

Appears after the main jQuery source file, and before our custom
JavaScript code.

•

Can be defined in two ways
– Utility functions defined directly on $ (an alias for jQuery)
– Methods to operate on a jQuery wrapped set (like jQuery methods)
Create a basic Plugin
•

The recommended guideline
– Prefix the filename with jquery.
– Follow that with the name of the plugin.

•

extend jquery's protype object
– jQuery.fn.methodName = methodDefinition;

•

wrap the assignment in an immediately invoked functions
(function($){
// code
})(jQuery);

•

Create a private scope ,allowing to extend using the $ not being
overwritten by another library

•

returns a jQuery object
Developing a Plug-in -Function
( function($){

$.fn.makeItBlue = function() {
return this.css('color','blue');
};
})(jQuery);

Invoking the plugins
$("#p1").makeItBlue();
Contained Function
•

The code to run plugin can be contained within a function

•

Used for writing a plugin that acts upon the jQuery result set on
each execution.

(function($){
$.fn.makeItBlueOrRed = function() {
return this.each(function(){
$(this).css('color',$(this).is('[id]') ? 'blue' : 'red');
});
};
})(jQuery);
Assoicating Function with Global Name space
(function($){
$.sum = function(array) {
var total = 0;
$.each(array, function(index, value) {
value = $.trim(value);
value = parseFloat(value) || 0;
total += value;
});
return total;
};
})(jQuery);
Using the Global Namespace
$(document).ready(function() {
var $inventory = $('#inv');
var quantities = $inventory.find('td:nth-child(3)')
.map(function(index, qty) {
return $(qty).text();
}).get();
var sum = $.sum(quantities);
$('#sum').text(sum);
});
$.extend()
•

Used to merges the contents of two or more objects and store
the result in the first object (or a new object)..

•

To merge object2 into object1
–

•

$.extend(object1, object2);

Used to override the default values for plugin to provide the user
with custom settings.
USING EXTEND
•

Use jQuery.fn.extend method instead of jQuery.fn.pluginName:

•

To add a more than one plugin methods to jQuery.
(function($){
$.fn.extend({
pluginname: function() {
return this.each(function() {
//code to be inserted here
});
}
});
Parameter Passing –Using Extend
(function($){
$.fn.selColor = function(opts) {
var defaults = {color:'red'};
var $originalElement = $(this);
var options = $.extend(defaults, opts);
return $(this).css('color',options.color);
};
}
)(jQuery);
Parameter Passing
(function($) {
$.fn.shadow = function(opts) {
var defaults = {
copies: 5,
opacity: 0.1,
copyOffset: function(index) {
return {x: index, y: index};
}
};
var options = $.extend(defaults, opts);
return this.each(function() {
var $originalElement = $(this);
Parameter Passing
for (var i = 0; i < opts.copies; i++) {
var offset = options.copyOffset(i);
$originalElement
.clone()
.css({
position: 'absolute',
left: $originalElement.offset().left + offset.x,
top: $originalElement.offset().top + offset.y,
margin: 0,
zIndex: -1,
opacity: opts.opacity
})
.appendTo('body');
}
});
}; })(jQuery);
Plugin

WIDGET FACTORY
Need for Widget Factory
•

The plugin becomes "stateful,“
– can examine, alter, or even completely reverse the effects of the plugin
after it has been applied.

•

User-supplied options are merged with customizable default
options automatically.

•

Multiple plugin methods are seamlessly combined into a single
jQuery method, accepting a string to identify which sub-method is
being called.

•

Custom event handlers triggered by the plugin get access to the
widget instance's data.

•

Consistent way to create and destroy widgets, get and set options,
Using Widget Factory
•

Used
– To create a plugin to create a new user interface element,
– To extend the jQuery UI library

•

The jQuery UI core contains a factory method $.widget()

•

Ensures code meets the API standards enjoyed by all jQuery UI
widgets.
Creating Widget
•

A plugin is created by the widget factory each time $.widget() is
called.

•

It accepts the name of the widget and a map of widget properties.

•

The name of the widget must be namespaced

•

When plugin gets called, functions will be executed within the
context of that instance.
– context is an object, not a DOM element.
– context is always a single object, never a collection.
Creating Widgets
•

Created with Namespaces with exactly one level deep
– $.widget(“com.simpler”,{ } );

•

First argument :
– is the widget's namespace used as the name of the widget method.

•

Second argument
– widget prototype, is an object literal that defines the specifics of the
widget.
– Definition of the widget, and is used when the widget is applied to
elements.
Invoking Widgets
•

$(“div").simpler();
– Widget method is used as the primary interface to the widget,
– Called when initially applying the widget to the element,
– Used for calling methods and reading and writing options and properties
on the widget.

•

When widgets are applied to elements, an instance of the widget is
created and stored inside each element.
Life cycle Functions in widgets
•

_create()
–
–
–
–
–

•

_init()
–
–
–
–

•

Invoked the first time the widget is applied to an element,
invoked.once per matched element in the jQuery object.
Used for Adding Classes
Storing References
Creating Elements
called after _create
called every time thereafter when the widget is invoked
place for setting up more complex initialization and reset functionality
It's common for widgets to not implement an _init method.

_destroy()
– To detach a widget from an element.
– Leave the element exactly like it was before the widget was attached.
– common tasks are to remove any CSS classes, detach any elements
Working with Widget Options
•

“this.element”
– jQuery object pointing to the element that was originally selected.

var msg=this.options.greet;
this.element.addClass("style1").text(msg);
•
•

Widgets have option method.
Allows to get and set options after initialization.
– Similar to .css() and .attr() methods:
– Can be used as as a setter or getter

•
•

As a setter, the plugin's _setOption method will be called for each
option that is being set.
Can specify a _setOption method to react to option changes.
Widgets with options
$.widget("com.simpler",{
options: {
msg :"Welcome to Widget Creations",
prefClass:"style1"
},
_create:function(){
var msg=this.options.msg;
this.element.addClass(this.options.prefClass).text(msg);
}

•
•
•

$(“div").simpler({greet:'Hello from widgetFactory'});
$(“div").simpler();
Adding Methods to a Widget
•

Public Functions can be defined in the Plugin

•

Defined in the jQuery.widget();

•

Can define "private" methods by prepending an underscore to the
function name.

•

To call a method on a plugin instance, you pass the name of the
method to the jQuery plugin.

•

If you are calling a method that accepts parameters, you simply
pass those parameters after the method name.
Widget with Public functions

options: {
msg :"Welcome to Widget Creations",
prefClass:"style1” },
_create:function(){
var msg=this.options.msg;
this.element.addClass(this.options.prefClass).text(msg);
},
showColor:function(cls)
{
if(cls===undefined) {
return this.options.prefClass; }
else {
this.options.prefClass=cls;
}
var val =$("<div></div>").appendTo("body").simpler();
alert(val.simpler("showColor"));
val.simpler("showColor","style2");
Widget with Private functions
showColor:function(cls)
{
if(cls===undefined) {
return this.options.prefClass;
}
else {
this.options.prefClass=this._checkClass(cls);
_checkClass:function(cls)
{
retVal=cls;
if(cls==='style2') {
retVal='newStyle2';
}
return retVal; }

} },
Qunit
•

Developed by John Resig as part of jQuery.

•

QUnit runs completely standalone.
<link rel="stylesheet" href="/resources/qunit.css">
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script src=“../js/qunit.js"></script>
<script src=“../js/tests.js"></script>
Test With truthy
•

<script>
test( "a basic test example", function() {
var value = $("div[id^='d']").size() % 2 ===0 ;
ok( value,
"There are only odd number of div starting with d -test fails”);
});

•

</script>
Test For Equal
•

<script>

•
•

test( "a basic test example", function() {
var value = $("div[id^='d']").size();

•
•

equal( value, 0, "Checking For div with d1" );
});

•

</script>
Download This presentation

http://sdrv.ms/1erDF7B

Contenu connexe

Tendances

Getting Started with jQuery
Getting Started with jQueryGetting Started with jQuery
Getting Started with jQueryAkshay Mathur
 
A Rich Web Experience with jQuery, Ajax and .NET
A Rich Web Experience with jQuery, Ajax and .NETA Rich Web Experience with jQuery, Ajax and .NET
A Rich Web Experience with jQuery, Ajax and .NETJames Johnson
 
Unobtrusive javascript with jQuery
Unobtrusive javascript with jQueryUnobtrusive javascript with jQuery
Unobtrusive javascript with jQueryAngel Ruiz
 
J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012ghnash
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginningAnis Ahmad
 
A Rich Web experience with jQuery, Ajax and .NET
A Rich Web experience with jQuery, Ajax and .NETA Rich Web experience with jQuery, Ajax and .NET
A Rich Web experience with jQuery, Ajax and .NETJames Johnson
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuerymanugoel2003
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutesSimon Willison
 
Javascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JSJavascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JSMin Ming Lo
 
SharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsSharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsMark Rackley
 
fuser interface-development-using-jquery
fuser interface-development-using-jqueryfuser interface-development-using-jquery
fuser interface-development-using-jqueryKostas Mavridis
 
JavaScript!
JavaScript!JavaScript!
JavaScript!RTigger
 
How to write easy-to-test JavaScript
How to write easy-to-test JavaScriptHow to write easy-to-test JavaScript
How to write easy-to-test JavaScriptYnon Perek
 
Prototype & jQuery
Prototype & jQueryPrototype & jQuery
Prototype & jQueryRemy Sharp
 

Tendances (20)

Getting Started with jQuery
Getting Started with jQueryGetting Started with jQuery
Getting Started with jQuery
 
jQuery Presentasion
jQuery PresentasionjQuery Presentasion
jQuery Presentasion
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
 
A Rich Web Experience with jQuery, Ajax and .NET
A Rich Web Experience with jQuery, Ajax and .NETA Rich Web Experience with jQuery, Ajax and .NET
A Rich Web Experience with jQuery, Ajax and .NET
 
Unobtrusive javascript with jQuery
Unobtrusive javascript with jQueryUnobtrusive javascript with jQuery
Unobtrusive javascript with jQuery
 
J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 
jQuery
jQueryjQuery
jQuery
 
D3.js and SVG
D3.js and SVGD3.js and SVG
D3.js and SVG
 
A Rich Web experience with jQuery, Ajax and .NET
A Rich Web experience with jQuery, Ajax and .NETA Rich Web experience with jQuery, Ajax and .NET
A Rich Web experience with jQuery, Ajax and .NET
 
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutes
 
Jquery-overview
Jquery-overviewJquery-overview
Jquery-overview
 
Javascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JSJavascript Application Architecture with Backbone.JS
Javascript Application Architecture with Backbone.JS
 
SharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsSharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentials
 
fuser interface-development-using-jquery
fuser interface-development-using-jqueryfuser interface-development-using-jquery
fuser interface-development-using-jquery
 
JavaScript!
JavaScript!JavaScript!
JavaScript!
 
How to write easy-to-test JavaScript
How to write easy-to-test JavaScriptHow to write easy-to-test JavaScript
How to write easy-to-test JavaScript
 
Prototype & jQuery
Prototype & jQueryPrototype & jQuery
Prototype & jQuery
 

En vedette

Iniciando com jquery
Iniciando com jqueryIniciando com jquery
Iniciando com jqueryDanilo Sousa
 
DOSUG Intro to JQuery JavaScript Framework
DOSUG Intro to JQuery JavaScript FrameworkDOSUG Intro to JQuery JavaScript Framework
DOSUG Intro to JQuery JavaScript FrameworkMatthew McCullough
 
Reuters: Pictures of the Year 2016 (Part 2)
Reuters: Pictures of the Year 2016 (Part 2)Reuters: Pictures of the Year 2016 (Part 2)
Reuters: Pictures of the Year 2016 (Part 2)maditabalnco
 
The Six Highest Performing B2B Blog Post Formats
The Six Highest Performing B2B Blog Post FormatsThe Six Highest Performing B2B Blog Post Formats
The Six Highest Performing B2B Blog Post FormatsBarry Feldman
 
The Outcome Economy
The Outcome EconomyThe Outcome Economy
The Outcome EconomyHelge Tennø
 

En vedette (6)

Iniciando com jquery
Iniciando com jqueryIniciando com jquery
Iniciando com jquery
 
DOSUG Intro to JQuery JavaScript Framework
DOSUG Intro to JQuery JavaScript FrameworkDOSUG Intro to JQuery JavaScript Framework
DOSUG Intro to JQuery JavaScript Framework
 
AngularJS
AngularJSAngularJS
AngularJS
 
Reuters: Pictures of the Year 2016 (Part 2)
Reuters: Pictures of the Year 2016 (Part 2)Reuters: Pictures of the Year 2016 (Part 2)
Reuters: Pictures of the Year 2016 (Part 2)
 
The Six Highest Performing B2B Blog Post Formats
The Six Highest Performing B2B Blog Post FormatsThe Six Highest Performing B2B Blog Post Formats
The Six Highest Performing B2B Blog Post Formats
 
The Outcome Economy
The Outcome EconomyThe Outcome Economy
The Outcome Economy
 

Similaire à J query module1

Similaire à J query module1 (20)

Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD CombinationLotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
 
J query presentation
J query presentationJ query presentation
J query presentation
 
J query presentation
J query presentationJ query presentation
J query presentation
 
Introduction to jquery mobile with Phonegap
Introduction to jquery mobile with PhonegapIntroduction to jquery mobile with Phonegap
Introduction to jquery mobile with Phonegap
 
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
 
Getting Started with jQuery
Getting Started with jQueryGetting Started with jQuery
Getting Started with jQuery
 
JQuery
JQueryJQuery
JQuery
 
JQuery
JQueryJQuery
JQuery
 
Advanced JQuery Mobile tutorial with Phonegap
Advanced JQuery Mobile tutorial with Phonegap Advanced JQuery Mobile tutorial with Phonegap
Advanced JQuery Mobile tutorial with Phonegap
 
JQuery UI
JQuery UIJQuery UI
JQuery UI
 
Web technologies-course 11.pptx
Web technologies-course 11.pptxWeb technologies-course 11.pptx
Web technologies-course 11.pptx
 
Jquery fundamentals
Jquery fundamentalsJquery fundamentals
Jquery fundamentals
 
Javascript libraries
Javascript librariesJavascript libraries
Javascript libraries
 
Jquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsJquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript Basics
 
jquery.ppt
jquery.pptjquery.ppt
jquery.ppt
 
Jquery 5
Jquery 5Jquery 5
Jquery 5
 
JQuery
JQueryJQuery
JQuery
 
Jquery
JqueryJquery
Jquery
 
J query ppt
J query pptJ query ppt
J query ppt
 
20131108 cs query by howard
20131108 cs query by howard20131108 cs query by howard
20131108 cs query by howard
 

Dernier

GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 

Dernier (20)

GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 

J query module1

  • 1.
  • 2. K.Srivatsan • • • IT Trainer Since 1991 Conducting Java Training Since 2004 About 40+ Corporate Clients
  • 3. Agenda 1. 2. 3. 4. 5. 6. 7. 8. 9. Introduction to jQuery Selection and DOM Traversal DOM and Attribute Manipulation CSS Styling and jQuery Event Handling with jQuery Effects and Custom Animations Ajax Calls with jQuery jQuery UI Plugin Development with jQuery
  • 5. Topics • Motivation for jQuery • History Of jQuery • What is jQuery • jQuery vs Custom JavaScript • jQuery vs Other JavaScript Libraries • Quick Start jQuery
  • 6. Motivation for jQuery • JavaScript has regained its prestige as rich internet applications and Ajax gaining popularity • Rapid Application development is made possible by the use of straightforward JavaScript , CSS and HTML. • Replace the cut-and-paste codes by full-featured JavaScript libraries and also to solve difficult cross-browser problems • Improved patterns for web development. – Lazy Initialization,Composite,Façade,Observer etc., • jQuery-driven code is easier to write, simpler to read, and fasterto execute than its plain JavaScript equivalent.
  • 7. Unobtrusive JavaScript • • • • Technique to have a clear separation of responsibilities A web page with structure, style, and behavior each partitioned Client-side code with the same level of care and respect as server-side code Extra work—But Not with JQuery.
  • 8. What is jQuery • jQuery is a JavaScript library that simplifies: – – – – – – • HTML element selection and document object model (DOM) traversal Element creation, deletion, and modification Event handling Animation Ajax interactions Custom widget integration (date picker, slider, dialogs, tabs, etc…) with jQuery UI jQuery is: – – – – – Free! Open-source lightweight footprint Cross-browser compatible Extensible! can write plugins or pick the one among a large list of existing ones.
  • 9. History of jQuery • The First Stable version of jQuery v1.0 was released in 2006 by a team headed by John Resig • The Latest version of jquery 1.9 and 2.0 are announced • Can be downloaded from the http://jquery.com/download/ • Minified Version : – compressed version with whitespaces and comments stripped out, shorter variable names in order to preserve bandwidth. – Can use normal jquery.js version for Debugging purpose
  • 10. Adding JQuery • Local System – Can add using <script> by downloading the minified version – <script type="text/javascript" src="path/to/jquery.min.js"> • Adding Jquery with Google CDN – http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js – http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js • To refer to the latest version of jQuery, – http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js
  • 11. Adding jQuery with Google CDN • Google has jQuery libraries on its Content delivery network and allows any website to use it for free. • Caching: The most important benefit is caching. If any previously visited site by user is using jQuery from Google CDN then the cached version will be used. It will not be downloaded again. • Reduce Load: It reduces the load on web server as it downloads from Google server's. • Serves fast : As Google has dozen's of different servers around the web and it will download the jQuery from whichever server closer to the user. • Parellel Downloading: As the js file is on a separate domain, modern browsers will download the script in parallel with scripts on your domain.
  • 12. The jQuery Function • $() function returns a JavaScript object containing an array of the DOM elements • Wraps the collected elements with extended functionality. • Return group of elements, which can be ready for another action. • To collect a group of elements, pass the selector to the jQuery function • • • $(selector) Or jQuery(selector) • $ is an alias for the jQuery() function
  • 13. Document Ready Handler • The onload handler, executes statements after the entire page is fully loaded. • This delays execution until after the DOM tree is created and all external resources are fully loaded and the page is displayed in the browser window. • jQuery provides a simple means to trigger the execution of code once the DOM tree has loaded and without waiting for external resources. jQuery(document).ready(function() { alert(jQuery('p').text()); }); $(function(){alert($ ('p').text()); });
  • 14.
  • 15. First JQUERY-Anonymous Functions <head> <script type="text/javascript" src="js/jquery-1.6.2.min.js"></script> <script type="text/javascript" > $(document).ready(function() { $("#msgId").html("<b>Hello From JQuery<b>"); }); </script> </head> <body> <div id="msgId"></div> </body>
  • 16. JQuery with Named Functions <script type="text/javascript" src="js/jquery-1.6.2.min.js"></script> <script type="text/javascript" > function setValue() { $("#msgId").html("Hello From JQuery") } $(function() { $("#echoButton").click(setValue); $("#echoButton").click(setValue()); }); </script> <p id="msgId">Example</p> <input type="button" value="Get TextFld Value" id="echoButton"/>
  • 18. Topics • • • • • • • • • • Basic Selectors Hierarchy Selectors Selection By Attribute Form Selectors Position Filters Other Filters Method Chaining DOM Traversal Filter Methods Advanced Method Chaining
  • 19. Basic Selectors • Basic jQuery selectors work the same as CSS selectors: • $(“*”) - // Selectors return a pseudo-array of jQuery elements • Selectors start with $(), representing the global jQuery function • It can take following arguments • • • Tag Name: Represents a tag name available in the DOM. Tag ID: Represents a tag available with the given ID in the DOM. Tag Class : Represents a tag available with the given class in the DOM. • If more than one element has the same id only the first matched element in the DOM will be returned
  • 20. Basic Selectors =$("#id1").text(); • <p id="id1">Java</p> • <p id="id2" class="style1">JEE</p> • $(".style1").text(); <div>Spring</div> =$(“div“).text();
  • 21. Controlling the context • $(“”, $()) • First argument -> is a selector, • Second argument -> denotes the context of the operation. • To Select the list Item inside a Division Identified with “colLef” • $("li", $(“#colLef")).css("border", "2px solid red"); -> function can have a second argument Element to Selection Context of Selection
  • 22. Selection By Attribute • $('a[href]'); – Selects all <a> elements that have an href attribute. • $('a[href=“Welcome.html"]'); – Selects all <a> elements whose href attribute exactly matches Welcome.html. • $(“div[id^=‘main’]”) – Select all div elements Id starting with main • $(“div[id$=‘name’]”) – Select all div elements Id END with name • $(“a[href*=‘msdn’]”) – Select all href elements containing msdn
  • 23. Working with DOM Attributes • • jQuery can be used easily manipulate an element's attributes Can be used to set and get a Attribute Value – Get Attribute Value: • • • • • var title = $("em").attr("title"); $("#divid").text(title); Set Attribute Value: The attr(name, value) method can be used to set the named attribute onto all elements in the wrapped set using the passed value. $("#myimg").attr("src", "/images/jquery.jpg");
  • 24. Applying Styles • The addClass( classes ) method can be used to apply defined style sheets onto all the matched elements. You can specify multiple classes separated by space. • $("em").addClass("selected"); $("#myid").addClass("highlight"); • attr( key, fn )Set a single property to a computed value, on all matched elements.removeAttr( name )Remove an attribute from each of the matched elements.hasClass( class )Returns true if the specified class is present on at least one of the set of matched elements.removeClass( class )Removes all or the specified class(es) from the set of matched elements.
  • 25. Hierarchy Selectors • $('#footer span'); – Selects the <span> elements that are descendants of the element with the id footer. • $('ul > li'); – Selects the <li> elements that are immediate children of <ul> elements. • $('h2 + p'); – Selects the <p> elements that are immediately preceded by an <h2> element. • $('h2 ~ p'); – Selects all <p> elements following an <h2> element that have the same parent as the <h2>element.
  • 26. Form Selectors • • • • • :input -> Input, textarea, select, and button elements :enabled -> Form elements that are enabled :disabled -> Form elements that are disabled :checked -> Radio buttons or checkboxes that are checked :selected -> Option elements that are selected • $(":checkbox")implies $("*:checkbox")). • var retVal =$("input:text#txtFld1").val(); • var retVal=$("input:radio[name=rad]:checked").val();
  • 27. Find Dropdown Selected Item <select name=“cities”> <select name=“cities”> <option value=“1”>Chennai</option> <option value=“1”>Chennai</option> <option value=“2”>Trichy</option> <option value=“2”>Trichy</option> <option value=“3”>Madurai</option> <option value=“3”>Madurai</option> </select> </select> $(“select[name=‘cities’] option:selected”).val() $(“select[name=‘cities’] option:selected”).val()
  • 28. Selecting by Position • a:first – This format of selector matches the first <a> element on the page. • p:odd – This selector matches every odd paragraph element. • p:even • • This selector matches every even paragraph element. ul li:last-child – chooses the last child of parent elements. In this example, the last <li> child of each <ul> element is matched
  • 29. Position Selection • • Can filter the elements selected based on their position in the collection $('.article:eq(2)'); – Selects the third element with the class article. – Elements in a collection are numbered starting with 0. • $('.article:gt(1)'); – From the collection of all elements with the class article, select all elements following the second one. • $('.article:lt(3)'); – From the collection of all elements with the class article, select up to the first three.
  • 30. Other Selections • $(p:contains(‘java')); – Selects all <p> elements that contain the string “java", either directly or in any of the child elements. – The text matching is case sensitive. • $('div:has(h2)'); – Selects all <div> elements that have at least one <h2> element as a descendant. • $('option:not(:selected)'); – Selects all <option> elements that are not selected. • $('p:hidden'); , $('p:visible'); – Selects all <p> elements that are hidden/visible. – An element is considered hidden if: • • • • It has a CSS display value of none It is a form element with type="hidden" Its width and height are explicitly set to 0 An ancestor element is hidden, so the element is not shown on the page
  • 31. jQuery Method Chaining • Selections return an instance of a jQuery object. • Returned instance can then invoke methods on the objects to manipulate the HTML elements it represents. • Using this we can chain method calls on the object. • $('.status') .css('backgroundColor','yellow') .attr('title', 'Training by Ramesh'); – This selects the elements with the class status, sets the background color of the selected elements to yellow, and then sets the title attribute of the selected elements.
  • 32. Methods • find() – From a set of selected elements to find descendants within the context of the currently selected elements. $s2=$(".style2"); $("#month_list1").find($s2).css("color","red"); • each() $("p").each(function(){ $(this).css("background-color","yellow"); }); $.each(names,function(i,val){ $("#msg2").append(val); });
  • 33. • Methods .filter() – Constructs a new jQuery object from a subset of the matching elements. – The supplied selector is tested against each element; all elements matching the selector will be included in the result. • • $("img").css("border","3px solid blue") .filter(“.style2") .css("border", "4px solid red"); find() vs Filters • filter : reduces the set of already matched elements, • find : gets descendants of the matched element
  • 35. Jquery Css • JQuery CSS selectors can be used to change CSS properties • CSS Methods do not modify the content of the jQuery object and they are used to apply CSS properties on DOM elements. • The method for CSS manipulation is css() • selector.css( PropertyName, PropertyValue ); • $("li").css("color", "red")
  • 36. Css Manipulations • • To Get the Current Css Style associated with an Element $(“div”).css(“background-color”); • To Set a New style to an Element • $(“div”).css(“float”, “left”); • • To Set Multiple style properties $(“div”).css({ “color”:”blue”, “padding”: “1em” “margin-right”: “0”, “marginLeft”: “10px” } • );
  • 37. Handling CSS Class • To add and remove class • $(“p”).removeClass(“blue”).addClass(“red”); • To add if absent, remove otherwise • $(“div”).toggleClass(“main”); • To test for class existance • if ($(“div”).hasClass(“main”)) { //… }
  • 39. Topics • • • • • • • • • • • DOM Traversal Creating Elements Inserting Elements Inserting an Element Before or After Another Element Inserting an Element as the First or Last Child of a Parent Mass Insertion Moving Elements Cloning (Copying) Elements Removing Elements Replacing Elements Element Content: HTML vs Text
  • 40. DOM Traversal • DOM Traversal can be done using the results of a selection • Can select the children, the parents, and the siblings of each element in the wrapped set. • $('h2').prev(); – Selects the set of elements that immediately precede <h2> elements. • $('h2').next('p'); – Selects the set of <p> elements that immediately follow <h2> elements. – if the element immediately following an <h2> is not a<p>, it is not included in the set of elements returned.
  • 41. DOM Traversal • $('#form-button').siblings('fieldset'); – Gets all the siblings that are <fieldset> • $('.menu-li2').parent(); – Gets the parent elements of elements having the class menu-li2 • $( "div" ).children().css( "border-bottom", "3px double red" ); – Get a set of elements containing all of the unique immediate children of each of the matched set of elements. • $("li").closest("ul .style2").css("border","3px solid blue"); – Get a set of elements containing the closest parent element that matches the specified selector, the starting element included.
  • 42. Creating Elements • There are two ways to create elements in jQuery: • A string with HTML markup as argument to the jQuery function: – $("<p>Hi there!</p>") : creates a New Paragraph – var menuli1 = $('<li class="menu-li1">About Us</li>'); • A string with HTML markup and a JavaScript object as the second argument, can be text, event callbacks and other HTML attributes. – var menuli1 = $('<li/>', { 'class': 'menu-li1', 'text': ‘About Us' });
  • 43. Inserting Elements • Create elements can be insert elements into a page. • Elements can be inserted: – – – – • Before an existing element After an existing element Inside a container element, at its beginning Inside a container element, at its end Two approaches to each method of inserting elements into a page: – Place the selected element(s) relative to another element – Place an element relative to the selected element(s)
  • 44. Inserting an Element Before Another Element • .insertBefore() – $(‘<ol><li>Chennai</li></ol>').insertBefore('#place_list1'); • .before() – $("#place_list1 :eq(2)").before("<li>Orissa<li>"); • .before(): – the selector expression preceding the method is the container before which the content is inserted. • .insertBefore() – the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted before the target container.
  • 45. Inserting an Element as the Last Child of a Parent • .append() : As the Last Child – newRow= "<tr><td>F105</td><td>jQuery</td></tr>"; • $("table").append(newRow); • .appendTo() • newRow =$("<li/>").html("Noida"); – newRow.appendTo("#place_list1");
  • 46. Cloning (Copying) Elements • • • Copy of element can be done with .clone() method , creates a “deep copy” of an existing selection. All descendant elements and text are duplicated. • .clone() returns a jQuery object of the duplicate, leaving the original selection in place. var $article=$('.article:first').clone(); $('#section').append($article);
  • 47. Removing Elements • There are two methods remove a selection: .detach() and.remove(). – both return the removed selection in case you want to restore it later. • Difference : – .remove(), selection loses its associated jQuery data and its attached events, which not a case with .detach(). – .detach() when you want to `reattach'' the selection to the page again in the future; – .remove() if you intend to discard the selection.
  • 48. Deleting Elements • • empty() : will remove all the contents of the selection. remove() : will remove the selection and its contents. • • • <div> <p><strong>foo</strong></p> </div> • $('p').empty(); • $('p').remove(); // --> "<div></div>" // --> "<div><p></p></div>" //
  • 49. Replacing Elements • To replace a selection : .replaceWith() and.replaceAll(). • .replaceWith() – Replace each element in the set of matched elements with the provided new content – returns the ones removed from the DOM. • $("#place_list1 :eq(3)").replaceWith("<li>Madurai</li>"); • .replaceAll() – Replace each target element with the set of matched elements. • $(“<div>Hello</div>”).replaceAll(“h1”);
  • 51. Topics • Events Overview • Binding An Event Handler • Binding Shortcut Methods • Unbinding Handlers and “One-Shot” Handlers • The Event Object • Event Delegation • Event Delegation And jQuery • live() vs .delegate()
  • 52. Event Handling • • • The event handling methods are core functions in jQuery. Event handlers are method that are called when "something happens" in HTML. The term "triggered (or "fired") by an event" is often used. • .click( handler(eventObject) ) • $("button").click(function(){ $("p").hide(); }); • <p>This is a paragraph.</p> • <button>Click me</button>
  • 53. JQuery Events • $(document).ready(function) – • $(selector).click(function) – • Triggers, or binds a function to the click event of selected elements $(selector).focus(function) – • Binds a function to the ready event of a document Triggers, or binds a function to the focus event of selected elements $(selector).mouseover(function) – Triggers, or binds a function to the mouseover event of selected elements
  • 55. Basic Syntax of Event Binding • .bind( eventType [, eventData ], handler(eventObject) ) • $(‘img’).bind(‘click’,function(event){alert(‘Message’;}); • Bind can also take list of events $('div').bind ('click keydown', function(e){ alert('event'); }); • $(‘img’).bind(‘click’,imgclick(event)); • Allows unbinding the function • $(‘img’).unbind(‘click’,imgclick());
  • 56. Bind multiple events simultaneously. $("div.test").bind({ click: function(){ $(this).addClass("active"); }, mouseenter: function(){ $(this).addClass("inside"); }, mouseleave: function(){ $(this).removeClass("inside"); } });
  • 57. Many Events & Handler • Attaching a handler to multiple events function handler(e){ alert('event'); } $('div').click(handler) .keydown(handler);
  • 58. ‘Event’ properties • event.target – ref to element triggering event • event.target.id – id of element triggering event • event.type – type of event triggered • event.data – second parm in the bind() func Various mouse coordinate properties Various keystroke related properties • •
  • 60. Event Name spacing • Can add a event within a specific namespace and then remove that events from that namespace. $("#img2").bind('click.ns2',mytoggler); $("#btn1").click(function(){ $(“img").unbind("click.ns2"); }); $("#btn2").click(function(){ $("#img2").bind("click.ns2",mytoggler); });
  • 61. Event Bubbling • When an event is triggered on an element in the DOM tree • It handled by the event handler • It also checks with the parent of that element to see if it has established a handler for the event type, and if so, it’s also invoked • Goes on up to the top of the DOM tree. • Because the event handling propagates upward like the bubbles ,is termed event bubbling.
  • 62. Event Handling Methods • preventDefault() – Prevents any default semantic action from occurring. • stopPropagation() – Stops any further propagation of the event up the DOM tree. – Additional events on the current target aren’t affected. – works with browser-defined events as well as custom events. • stopImmediatePropagation() – Stops all further event propagation including additional events on the current target.
  • 63. Event Bubbling $( 'h1,a' ).on( 'click', function( event ) { event. stopPropagation(); alert( $( this ).attr( 'id' ) ); } <h1 class="style1" id="hd1"> <a href="#1" id="anch"> <span id="sp">Using Events</span> </a> </h1> .stopPropagation() on the event object — stop the propagation of events up
  • 64. Preventing the default action • preventDefault() – Called on the event object, used to prevent the default action of an event; $( 'a' ).on( 'click', function( event ) { event.preventDefault(); alert('I was just clicked!' ); });
  • 65. Live() Method • jQuery can attach event handler to any future elements which matches the original selector, • Live events do not bubble in the traditional manner and cannot be stopped using stopPropagation or stopImmediatePropagation. • To remove a live event die() method is used • • • • $('#listLive>li') .live('mouseover', function(){ $(this).addClass('selected'); }) .live('mouseout', function(){ $(this).removeClass('selected'); }); });
  • 66. die() Method • Remove all event handlers previously attached using .live() from the elements • This method is analogous to calling .unbind() with no arguments, function aClick() { $("div").show().fadeOut("slow"); } $("#bind").click(function () { $("#theone").live("click", aClick).text("Can Click!"); }); $("#unbind").click(function () { $("#theone").die("click", aClick).text("Does nothing..."); });
  • 67. On Method • .on( events [, selector ] [, data ], handler(eventObject) ) • Introduced with jQuery 1.7, • Its combination of bind, live method. • Bind $( "#members li a" ).on( "click", function( e ) {} ); $( "#members li a" ).bind( "click", function( e ) {} ); • Live $( document ).on( "click", "#members li a", function( e ) {} ); $( "#members li a" ).live( "click", function( e ) {} );
  • 68. On Method $(function(){ $(document.body).on('mouseover',"#tab tr", function(){ $(this).addClass("selected"); }) .on('mouseout',"#tab tr", function(){$(this).removeClass("selected")}); $('#add').click(function(){ $('#tab').append('<tr><td>1</td><td>Jquery</td></tr>'); }); });
  • 69. Triggering Events • trigger( eventType, data ) – Execute all handlers and behaviors attached to the matched elements for the given event type. – Data to be passed to the handlers as the second parameter (after the event instance). • • • $("#button1").bind("click", (function () { alert("Button 1 is clicked!"); })); • $("#button2").bind("click", (function () { alert("Button 2 is clicked!"); $("#button1").trigger("click"); }));
  • 70. Creating Custom Events • Can Create our own custom events using jQuery event binder Methods • Done by providing event binder method with a unique name for a custom event. • Custom events are programmatically triggered using the jQuery trigger() method.
  • 71. Creating Custom Events $(function(){ $("p").on("myCustomEvent", function(event,d){ alert("event"+ event.type + "data"+ d.name); $(this).text(" I am triggered by Custom event !"); }); $("button").click(function (e ) { var e = jQuery.Event( "myCustomEvent"); $("p").trigger(e,{name:'ram'}); }); });
  • 72. ContextMenu - Event • The contextmenu event is fired when the right button of the mouse is clicked before the context menu is displayed • Can use this Event with jQuery to Disable Right Click on a Page $(document).bind('contextmenu',function(){ alert('right button disabled for security'); return false; });
  • 74. Showing and hiding elements • Showing or hiding elements are simple and pop elements into existence or make them instantly vanish! • show() – to show the elements in a wrapped set, and hide() to hide them. • jQuery hides elements by changing their style.display properties to none. • If an element in the wrapped set is already hidden, it will remain hidden but still be returned for chaining.
  • 75. Useful Functions • • • • .hide() – display:none .show() – display:true .toggle(func1, func2) – first click calls func1, next click executes func2 .hover(over, out) – mouseover, mouseout
  • 76. Useful Functions • • .hide() .show() – $(“div”).show(); – $(“div”).show(“slow”); – $(“div”).hide(“fast”); • .toggle(func1, func2) – first click calls func1, next click executes func2 • .hover(over, out) – mouseover, mouseout
  • 77. Fading Elements • fadeIn(speed,callback) – Causes any matched elements that are hidden to be shown by gradually changing their opacity to their natural value. – This value is either the opacity originally applied to the element, or 100 percent. – The duration of the change in opacity is determined by the speed parameter. – Only hidden elements are affected. $(document).ready(function(){ $("button").click(function(){ $("#div1").fadeIn(); $("#div2").fadeIn("slow"); $("#div3").fadeIn(3000); }); });
  • 78. Fading Elements • fadeOut(speed,callback) – Causes any matched elements that aren’t hidden to be removed from the display by gradually changing their opacity to 0 percent and then removing the element from the display. – The duration of the change in opacity is determined by the speed parameter. $(document).ready(function(){ $("button").click(function(){ $("#div1").fadeIn(); $("#div2").fadeIn("slow"); $("#div3").fadeIn(3000); }); });
  • 79. Fading Elements • fadeTo(speed,opacity,callback) • Doesn’t remember the original opacity of an element. • Used to explicitly change the opacity to a specific value. $(document).ready(function(){ $("button").click(function(){ $("#div1").fadeTo("slow",0.15); $("#div2").fadeTo("slow",0.4); $("#div3").fadeTo("slow",0.7); }); });
  • 80. Sliding Elements Up and down • 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. • As with hide()and show(), the slide effects have a related method that will toggle the elements between hidden and revealed: slideToggle(). • slideDown(speed,callback) – Causes any matched elements that are hidden to be shown by gradually increasing their vertical size. Only hidden elements are affected. slideUp(speed,callback) – Causes any matched elements that are displayed to be removed from the display by gradually decreasing their vertical size. •
  • 82. Reset Predefined Spees – jQuery.fx.speeds.fast = 50; • Create a new pre-defined speed – jQuery.fx.speeds.turtle = 3000;
  • 83. Creating Custom Animation • • • Core Library has few effects, can use Pluggins to add special effects The animate() wrapper method, allows us to apply custom animated effects to the elements of a wrapped set. The animate( ) method performs a custom animation with a set of CSS properties. Done gradually, animating the effect at the chosen speed: • selector.animate( params, [duration, easing, callback] ); • params: • – • duration: – • This is optional parameter representing how long the animation will run. easing: ( linear and swing) – • A map of CSS properties that the animation will move toward. This is optional parameter representing which easing function to use for the transition callback: – This is optional parameter representing a function to call once the animation is complete.
  • 85. Chaining Animation $(“div”).animate({width: “90%”},100) $(“div”).animate({width: “90%”},100) .animate({opacity: 0.5},200) .animate({opacity: 0.5},200) .animate({borderWidth: “5px”}); .animate({borderWidth: “5px”}); By default animations are queued and than performed one by one
  • 86. Controlling Animations Sync $(“div”) $(“div”) .animate({width: “90%”}, .animate({width: “90%”}, {queue:false, duration:1000}) {queue:false, duration:1000}) .animate({opacity : 0.5}); .animate({opacity : 0.5}); The first animation will be performed immediately without queuing
  • 87. Stopping Animations • stop(clearQueue,gotoEnd) – Halts any animations that are currently in progress for the elements in the matched set. • clearQueue (Boolean) – If specified and set to true, not only stops the current animation,but any other animations waiting in the animation queue. • gotoEnd (Boolean) – If specified and set to true, advances the current animation to its logical end (as opposed to merely stopping it).
  • 90. XMLHttpRequest • JavaScript object • Adopted by modern browsers – Mozilla™, Firefox, Safari, and Opera • Communicates with a server via standard HTTP GET/POST • XMLHttpRequest object works in the background for performing asynchronous communication with the backend server – Does not interrupt user operation
  • 91. Server-Side AJAX Request Processing • Server programming model remains the same – It receives standard HTTP GETs/POSTs – Can use Servlet, JSP, JSF, ... • With minor constraints – More frequent and finer-grained requests from client – Response content type can be • text/xml • text/plain • text/json • text/javascript
  • 92. Ajax with jQuery • $.get( url, [data], [callback], [datatype] ) – Load a remote page using an HTTP GET request. • $.getJSON( url, [data], [callback] ): – Load JSON data using an HTTP GET request. • $.getScript( url, [callback] ) – Loads and executes a JavaScript file using an HTTP GET request • .$.post( url, [data], [callback], [type] ) – Load a remote page using an HTTP POST request. • $.load( url, [data], [callback] ) – Load HTML from a remote file and inject it into the DOM • $.ajax(): – To do something when XHR fails, or to specify options on the fly.
  • 93. Load Method • • • • • • This method is called on a selection , Fetches the HTML from a URL and uses the returned HTML to populate the selected element. In addition to URL optionally can provide a selector , jquery will fetech only the matching content from the returned HTML Load Method with Post Data $("#disDiv").html(ld_img).load('Response.jsp', {"name":name} ); Load Method with GET Data – $("#disDiv").html(ld_img).load('Response.jsp', '&name='+name);
  • 94. $.ajax() • Powerful and straightforward way of creating ajax request • It takes an configuration object that has the all instructions required • Has the ability to specify success and failure callback • Configuration object can be defined separately makes it easier to write and reuse the code
  • 95. Making an Ajax Call $(document).ready(function(){ $("button").click(function(){ $.ajax({url:"First.Jsp", success:function(result){ $("div").html(result); }}); });}); </script> </head> <body> <div><h2>Let AJAX change this text</h2></div> <button>Change Content</button> </body> </html>
  • 96. Get and Post Method • • • $.get(“Sample.jsp", function(data) { alert("Data Loaded: " + data); }); • jQuery.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] ) • • To Post the Form Data $.post(“Sample.jsp", { name: “Ramesh", age: "29" } ); • • To Post the Entire Form Data $.post(“Sample.jsp", $("#frm").serialize());
  • 97. $.ajax() • $.ajax() method. – Used to make Ajax Calls var options = { type: 'GET', url: ‘ProcessData.jsp', dataType: 'html', error: function(xhr, textStatus, errorThrown) { alert('An error occurred! ' + errorThrown); }, success: function(data, textStatus) { $('body').append( data ); } }; $.ajax( options );
  • 98. Load Java Script Show.js function show() { data =new Array("Head First Java","Spring in Action","thinking in Java"); } var scriptUrl = "../js/Show.js"; $.getScript(scriptUrl,function(){ show(); $("#disDiv").html(data); });
  • 99. JQuery AJAX Events: • • • • • • • • The methods used during the life cycle of AJAX call progress. Based on different events/stages following methods are available: ajaxComplete( callback ) Attach a function to be executed whenever an AJAX request completes. ajaxStart( callback ) – Attach a function to be executed whenever an AJAX request begins and there is none already active .ajaxError( callback ) – Attach a function to be executed whenever an AJAX request fails. ajaxSend( callback ) – Attach a function to be executed before an AJAX request is sent. ajaxStop( callback ) – Attach a function to be executed whenever all AJAX requests have ended ajaxSuccess( callback ) – Attach a function to be executed whenever an AJAX request completes successfully.
  • 100. Ajax Global Events • Events that are broadcast to all elements in the DOM, triggering any handlers which may be listening. $("#loading").bind("ajaxSend", function(){ $(this).show(); }) .bind("ajaxComplete", function(){ $(this).hide(); }); • Can be disabled for a particular Ajax request $.ajax({ url: "test.html", global: false, });
  • 101. Local Events • These are callbacks that you can subscribe to within the Ajax request object $.ajax({ beforeSend: function(){ }, complete: function(){ } });
  • 102. Deprecated Methods since 1.8 • The jqXHR.success(), jqXHR.error(), jqXHR.complete() callbacks are deprecated as of jQuery 1.8. • jqXHR.done(function(data, textStatus, jqXHR) {}); – An alternative construct to the success callback option, the .done() method replaces the • jqXHR.fail(function(jqXHR, textStatus, errorThrown) {}); – An alternative construct to the error callback option • jqXHR.always(function(data|jqXHR, textStatus, jqXHR| errorThrown) { }); – An alternative construct to the complete callback option
  • 103. Example var jqxhr = $.ajax( "example.jsp" ).done(function() { alert("success"); }) .fail(function() { alert("error"); }) .always(function() { alert("complete"); });
  • 104. JSON: JavaScript Object Notation. • • • • • Lightweight text-data interchange format "self-describing" and easy to understand Uses JavaScript syntax for describing data objects JSON parsers and JSON libraries exists for many different programming languages JavaScript program can use the eval() to get native JS objects. { "employees": [ { "firstName":"John" , "lastName":"Doe" }, { "firstName":"Anna" , "lastName":"Smith" }, { "firstName":"Peter" , "lastName":"Jones" } ] } The employees object is an array of 3 employee records (objects).
  • 105. JSON Syntax Rules • JSON syntax is a subset of the JavaScript object notation syntax: – – – – Data is in name/value pairs Data is separated by commas Curly braces hold objects Square brackets hold arrays • • • JSON Name/Value Pairs JSON data is written as name/value pairs. A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value: • "firstName" : "John“ equivalent to firstName = "John"
  • 106. Working With Json Data • Servers return JSON string against a request. • getJSON() parses the returned JSON string and makes the resulting string available to the callback function • [selector].getJSON( URL, [data], [callback] ); • data: – An object whose properties serve as the name/value pairs used to construct a query string to be appended to the URL, or a preformatted and encoded query string. • Callback: – The data value resulting from digesting the response body as a JSON string is passed as the first parameter to this callback, and the status as the second.
  • 107. Generating JSON Data User user = new User(101,”Ramesh); ObjectMapper mapper = new ObjectMapper(); try { mapper.writeValue(new File(“user.json"), user); System.out.println(mapper.writeValueAsString(user)); } catch (Exception e) { e.printStackTrace(); }
  • 108. Working With Json Data $(document).ready(function() { $("#driver").click(function(event){ $.getJSON('user.json', function(jd) { $('#id1').html('<p> Name: ' + jd.name + '</p>'); $('#id1').append('<p>Age : ' + jd.age+ '</p>'); }); }); }); <div id="id1" > </div> <input type="button" id="driver" value="Load Data" />
  • 109. Ajax with JSON Data $.ajax({ type: "GET", cache: false, contentType: "application/json; charset=utf-8", url: 'JsonResponse.jsp', async: true, success: function (data, textStatus, jqXHR) { if (textStatus == "success") { $("#disDiv").text(data); } }, error: function (jqXHR, textStatus, errorThrown) { handleError(jqXHR); } }); }
  • 111. jQuery UI - Overview • Provides abstractions for low-level interaction and animation, advanced effects and high-level, themeable widgets • Built on top of the jQuery JavaScript Library • Used to build highly interactive web applications • Javascript UI libraries: o YUI - Yahoo! User Interface library o digit - Dojo User Interface library o Protoype UI
  • 112. UI Library • Jquery has various Widgets using UI Libraries • Required Libraries are downloaded and added to the pages • CSS • <link rel="stylesheet" href="themes/base/jquery.ui.all.css"> • JS Libraries <script src="js/jquery-1.9.0.js"></script> <script src="ui/jquery.ui.core.js"></script> <script src="ui/jquery.ui.widget.js"></script> <script src="ui/jquery.ui.resizable.js"></script> Can add the Appropriate .js files,for the required UI Effects
  • 113. UI Library Based Effects: • Call effect on any DOM element • .effect(effect,[options],[speed],[callback]} o speed  "slow", "normal", or "fast" or # of milliseconds o callback  function called after effect is completed • Blind : Blinds the element away or shows it by blinding it in • Explode :Explodes the element into multiple pieces. • Fold : Folds the element like a piece of paper. • Highlight : Highlights the background with a defined color. • Pulsate :Pulsates the opacity of the element multiple times • Scale : Shrink or grow an element by a percentage factor. • Shake :Shakes the element vertically or horizontally n-times. • Slide : Slides the element out of the viewport
  • 114. UI Library Based Effects • • <script src="../ui/jquery-ui.core.js"></script> <script src="../ui/jquery-ui.js"></script> • $(function() { • $("#button").click(function() { • • • • • $("#effect").effect('blind',500,function(){ alert("Done"); }); }); });
  • 115. Draggable • Make the selected elements draggable by mouse. • Can also drag& drop, Using Droppable plugin, which provides a drop target for draggables. • Initialize the draggable with the addClasses option specified: • $( ".selector" ).draggable({ addClasses: false }); • axisType: Constrains dragging to either the horizontal (x) or vertical (y) axis. Possible values: "x", "y". • $( ".selector" ).draggable({ axis: “y" });
  • 116. Draggable $(function() { $( "#draggable" ).draggable(); }); </script> </head> <body> <div id="draggable" class="ui-widget-content"> <p>Using Drags</p> </div>
  • 117. Droppable • Makes selected elements droppable • They accept being dropped on by draggables. • Can specify which draggables each will accept. • $( "#draggable" ).draggable(); • Can Initialize the droppable with the accept option specified: • $( ".selector" ).droppable({ accept: “#jsp " });
  • 118. Droppable $(function() { $(".square").draggable(); $(".squaredotted").droppable({ drop : function(event, ui) { $("#info").html("dropped!"); }, over : function(event, ui) { $("#info").html("moving in!"); }, out : function(event, ui) { $("#info").html("moving out!"); } }); });
  • 119. Droppable- Accept $(".square").draggable(); $("#serverSideScript").droppable({ accept : "#jsp", drop : function(event, ui) { $(this).css("background-color", "lightgreen") }, out : function(event, ui) { $(this).css("background-color", "") } • <div id="jsp" class="square">Jsp</div> • <div id="serverSideScript" class="squaredotted">Server Side Scripting Language</div>
  • 120. Resizeable • The jQuery UI Resizable plugin makes selected elements resizable • Has a draggable resize handles • Can be configured with one or more handles as well as min and max width and height. $(function() { $( "#resizable" ).resizable( minHeight:'140',minWidth:'100', maxHeight:'300',maxWidth:'250'}); });
  • 121. Buttons • Enhances standard form elements like buttons, inputs and anchors to themeable buttons with appropriate hover and active styles. • $( ".selector" ).button({ disabled: true }); $( ".selector" ).button( { icons: { primary: "ui-icon-gear", secondary: "ui-icon-triangle-1-s" } }); $( ".selector" ).button({ label: "custom label" });
  • 123. Date Picker • Used in textfield to pop up calendar. • Choosing day from calendar puts date string into textfield • HTML • <input type="text" id="date-field"/> • JavaScript • “datepicker()” called on the textfield – $("#date-field").datepicker();
  • 124. Date Picker <form action=#"> From: <input type="text"/> Departure Date: <input type="text" id="start-date"/> Return Date: <input type="text" id="end-date"/> <input type="button" value="Show Flights"/> <input type="button" value="Show Hotels"/> </form> $(function() { $("#start-date").datepicker(); $("#end-date").datepicker({ changeMonth: true, numberOfMonths: 2 }); });
  • 125. Main Option of DatePicker • $(function() { $("#bDate").datepicker({buttonImage: "../images/calendar.gif", buttonImageOnly: true,showOn: "button"}); }); • buttonImage : – A URL of an image to use to display the datepicker when the showOn option is set to "button" or "both". • buttonImageOnly: • Just the button image only or inside a button element. • Used if the buttonImage option has also been set.
  • 127. Accordion Panel • Horizontally stacked panels with wide tabs • HTML – Need container to hold the tabs • Create alternating pairs of text with links and content <h2><a href="#">Panel 1</a></h2> <div>Content for Panel 1</div> <h2><a href="#">Panel 2</a></h2> <div>Content for Panel 2</div> • • JavaScript Call “accordion()” on the div container $("#main-accordion-panel-div").accordion();
  • 128. Accordian <script> $(document).ready(function() { $(“#accrd ").accordion(); }); </script> • $("#accrd1").accordion({event :'mouseover'}); var icons = { header: "ui-icon-circle-arrow-e", activeHeader: "ui-icon-circle-arrow-s" }; • $("#accrd2").accordion({icons: icons});
  • 130. Tabbed Panel • • Tabbed panel where clicking tabs changes content inside Make a div container to hold the tabs – • • <div id="main-tabbed-panel-div">…</div> Include a ul list containing internal hyperlinks <ul> <li><a href="#panel1">Go to Panel 1</a></li> <li><a href="#panel2">Go to Panel 2</a></li> </ul> • Call “tabs()” on the div container $("#main-tabbed-panel-div").tabs();
  • 131. Tab Panel <script> $(document).ready(function() { $("#tabs").tabs(); }); </script> <div id="tabs"> <ul> <li><a href="#fragment-1"><span>One</span></a></li> <li><a href="#fragment-2"><span>Two</span></a></li> <li><a href="#fragment-3"><span>Three</span></a></li> </ul> <div id="fragment-1"> <p>First tab is active by default:</p> <pre><code>This is the First Tab Panel</code></pre> </div>
  • 132. Tab- Options • collapsible (default: false) – Click on selected tab to hide it – $("#main-id").tabs({ collapsible: true }); • disabled (default: empty array) – An array of tab numbers (0-based) that should be disabled on startup • event (default: click) – The type of event that should initiate tab selection – $("#main-id").tabs({ event: "mouseover" });
  • 133. AutoComplete • Autocomplete enables users to quickly find and select from a prepopulated list of values as they type, leveraging searching and filtering. • The plugin starts searching for entries that match and displays a list of values to choose from. • You can pull data in from a local or remote source: $( "#tags" ).autocomplete({ source: availableTags });
  • 134. AutoComplete $(function() { var scripts= ["JavaScript“,"Lisp“,"Ruby“, "Scala“, "Scheme” ]; $( "#tags" ).autocomplete({source: scripts,select: function( event, ui ) { alert("Item Selected"+ui.item.value); } }); • }); <div class="ui-widget"> <label for="tags">Tags: </label> <input id="tags" /> </div>
  • 135. Dialog • • A way delivering information to the user. Created by Selecting the content to become the body and the dialog() method is applied. • dialog(options) – Draggable,height,width,focus,show,title etc., • dialog('disable') • dialog('open') – Opens a closed dialog box. $(function() { $( "#dialog" ).dialog(); });
  • 136. Dialog • • • • • $("#diaMsg").dialog({modal: false,buttons:{ Ok:function(){$(this).dialog("close"); $("#diaAnch1").hide(); $("#moreCourse").show(); } • Modal: – If set to true, the dialog will have modal behavior; – other items on the page will be disabled and cannot be interacted . • Buttons: – Buttons that should be displayed on the dialog.
  • 137. Creating Menu • Can create Menu with mouse and keyboard interactions for navigation. • Created from any valid markup that has parent/child relationship and each menu item has an anchor. <ul id="menu"> <li><a href="#">Item 1</a></li> <li><a href="#">Item 2</a> <ul> <li><a href="#">Item 2-1</a></li> <li><a href="#">Item 2-2</a></li> </ul> </li> <li><a href="#">Item 3</a></li> </ul>
  • 138. Menu • $( ".selector" ).menu({ disabled: true }); • $( ".selector" ).menu({ icons: { submenu: "ui-icon-circle-trianglee" } });
  • 139. Sliders • To make selected elements into sliders. • The handle can be moved with the mouse or the arrow keys. $( "#slider-range" ).slider( { range: true, min: 0, max: 500, values: [ 75, 300 ], slide: function( event, ui ) { $( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] ); } });
  • 141. Plugin • A plug-in is piece of code written in a standard JavaScript file • Plugin works with a collection of elements • Appears after the main jQuery source file, and before our custom JavaScript code. • Can be defined in two ways – Utility functions defined directly on $ (an alias for jQuery) – Methods to operate on a jQuery wrapped set (like jQuery methods)
  • 142. Create a basic Plugin • The recommended guideline – Prefix the filename with jquery. – Follow that with the name of the plugin. • extend jquery's protype object – jQuery.fn.methodName = methodDefinition; • wrap the assignment in an immediately invoked functions (function($){ // code })(jQuery); • Create a private scope ,allowing to extend using the $ not being overwritten by another library • returns a jQuery object
  • 143. Developing a Plug-in -Function ( function($){ $.fn.makeItBlue = function() { return this.css('color','blue'); }; })(jQuery); Invoking the plugins $("#p1").makeItBlue();
  • 144. Contained Function • The code to run plugin can be contained within a function • Used for writing a plugin that acts upon the jQuery result set on each execution. (function($){ $.fn.makeItBlueOrRed = function() { return this.each(function(){ $(this).css('color',$(this).is('[id]') ? 'blue' : 'red'); }); }; })(jQuery);
  • 145. Assoicating Function with Global Name space (function($){ $.sum = function(array) { var total = 0; $.each(array, function(index, value) { value = $.trim(value); value = parseFloat(value) || 0; total += value; }); return total; }; })(jQuery);
  • 146. Using the Global Namespace $(document).ready(function() { var $inventory = $('#inv'); var quantities = $inventory.find('td:nth-child(3)') .map(function(index, qty) { return $(qty).text(); }).get(); var sum = $.sum(quantities); $('#sum').text(sum); });
  • 147. $.extend() • Used to merges the contents of two or more objects and store the result in the first object (or a new object).. • To merge object2 into object1 – • $.extend(object1, object2); Used to override the default values for plugin to provide the user with custom settings.
  • 148. USING EXTEND • Use jQuery.fn.extend method instead of jQuery.fn.pluginName: • To add a more than one plugin methods to jQuery. (function($){ $.fn.extend({ pluginname: function() { return this.each(function() { //code to be inserted here }); } });
  • 149. Parameter Passing –Using Extend (function($){ $.fn.selColor = function(opts) { var defaults = {color:'red'}; var $originalElement = $(this); var options = $.extend(defaults, opts); return $(this).css('color',options.color); }; } )(jQuery);
  • 150. Parameter Passing (function($) { $.fn.shadow = function(opts) { var defaults = { copies: 5, opacity: 0.1, copyOffset: function(index) { return {x: index, y: index}; } }; var options = $.extend(defaults, opts); return this.each(function() { var $originalElement = $(this);
  • 151. Parameter Passing for (var i = 0; i < opts.copies; i++) { var offset = options.copyOffset(i); $originalElement .clone() .css({ position: 'absolute', left: $originalElement.offset().left + offset.x, top: $originalElement.offset().top + offset.y, margin: 0, zIndex: -1, opacity: opts.opacity }) .appendTo('body'); } }); }; })(jQuery);
  • 153. Need for Widget Factory • The plugin becomes "stateful,“ – can examine, alter, or even completely reverse the effects of the plugin after it has been applied. • User-supplied options are merged with customizable default options automatically. • Multiple plugin methods are seamlessly combined into a single jQuery method, accepting a string to identify which sub-method is being called. • Custom event handlers triggered by the plugin get access to the widget instance's data. • Consistent way to create and destroy widgets, get and set options,
  • 154. Using Widget Factory • Used – To create a plugin to create a new user interface element, – To extend the jQuery UI library • The jQuery UI core contains a factory method $.widget() • Ensures code meets the API standards enjoyed by all jQuery UI widgets.
  • 155. Creating Widget • A plugin is created by the widget factory each time $.widget() is called. • It accepts the name of the widget and a map of widget properties. • The name of the widget must be namespaced • When plugin gets called, functions will be executed within the context of that instance. – context is an object, not a DOM element. – context is always a single object, never a collection.
  • 156. Creating Widgets • Created with Namespaces with exactly one level deep – $.widget(“com.simpler”,{ } ); • First argument : – is the widget's namespace used as the name of the widget method. • Second argument – widget prototype, is an object literal that defines the specifics of the widget. – Definition of the widget, and is used when the widget is applied to elements.
  • 157. Invoking Widgets • $(“div").simpler(); – Widget method is used as the primary interface to the widget, – Called when initially applying the widget to the element, – Used for calling methods and reading and writing options and properties on the widget. • When widgets are applied to elements, an instance of the widget is created and stored inside each element.
  • 158. Life cycle Functions in widgets • _create() – – – – – • _init() – – – – • Invoked the first time the widget is applied to an element, invoked.once per matched element in the jQuery object. Used for Adding Classes Storing References Creating Elements called after _create called every time thereafter when the widget is invoked place for setting up more complex initialization and reset functionality It's common for widgets to not implement an _init method. _destroy() – To detach a widget from an element. – Leave the element exactly like it was before the widget was attached. – common tasks are to remove any CSS classes, detach any elements
  • 159. Working with Widget Options • “this.element” – jQuery object pointing to the element that was originally selected. var msg=this.options.greet; this.element.addClass("style1").text(msg); • • Widgets have option method. Allows to get and set options after initialization. – Similar to .css() and .attr() methods: – Can be used as as a setter or getter • • As a setter, the plugin's _setOption method will be called for each option that is being set. Can specify a _setOption method to react to option changes.
  • 160. Widgets with options $.widget("com.simpler",{ options: { msg :"Welcome to Widget Creations", prefClass:"style1" }, _create:function(){ var msg=this.options.msg; this.element.addClass(this.options.prefClass).text(msg); } • • • $(“div").simpler({greet:'Hello from widgetFactory'}); $(“div").simpler();
  • 161. Adding Methods to a Widget • Public Functions can be defined in the Plugin • Defined in the jQuery.widget(); • Can define "private" methods by prepending an underscore to the function name. • To call a method on a plugin instance, you pass the name of the method to the jQuery plugin. • If you are calling a method that accepts parameters, you simply pass those parameters after the method name.
  • 162. Widget with Public functions options: { msg :"Welcome to Widget Creations", prefClass:"style1” }, _create:function(){ var msg=this.options.msg; this.element.addClass(this.options.prefClass).text(msg); }, showColor:function(cls) { if(cls===undefined) { return this.options.prefClass; } else { this.options.prefClass=cls; } var val =$("<div></div>").appendTo("body").simpler(); alert(val.simpler("showColor")); val.simpler("showColor","style2");
  • 163. Widget with Private functions showColor:function(cls) { if(cls===undefined) { return this.options.prefClass; } else { this.options.prefClass=this._checkClass(cls); _checkClass:function(cls) { retVal=cls; if(cls==='style2') { retVal='newStyle2'; } return retVal; } } },
  • 164. Qunit • Developed by John Resig as part of jQuery. • QUnit runs completely standalone. <link rel="stylesheet" href="/resources/qunit.css"> <div id="qunit"></div> <div id="qunit-fixture"></div> <script src=“../js/qunit.js"></script> <script src=“../js/tests.js"></script>
  • 165. Test With truthy • <script> test( "a basic test example", function() { var value = $("div[id^='d']").size() % 2 ===0 ; ok( value, "There are only odd number of div starting with d -test fails”); }); • </script>
  • 166. Test For Equal • <script> • • test( "a basic test example", function() { var value = $("div[id^='d']").size(); • • equal( value, 0, "Checking For div with d1" ); }); • </script>

Notes de l'éditeur

  1. Now let&apos;s talk about XMLHttpRequest a bit. It is a JavaScript object, which means it gets created within a JavaScript code. The XMLHttpRequest JavaScript object is supported in most modern browsers. It is the AJAX engine that performs the HTTP request/response interaction with the backend web application in asynchronous fashion.
  2. Now, how does server side web application handle the AJAX interaction with the browser? Well as far as Server side code is concerned, it is just another HTTP request that comes in. The server side does not even know the browser is sending the HTTP request in asynchronous fashion and it should not. What this means is that the server side web application can use any server side technology of its choice such as servlet, JSP, JSF, Struts, or whatever. The server side application however has minor constraints. First, it is possible the client might send more frequent and finer grained requests. The response type can be text/xml, text/plain, text/json, or text/javascript.