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 S...
1

INTRODUCTION TO JQUERY
Topics
•

Motivation for jQuery

•

History Of jQuery

•

What is jQuery

•

jQuery vs Custom JavaScript

•

jQuery vs Oth...
Motivation for jQuery
•

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

•...
Unobtrusive JavaScript
•
•
•
•

Technique to have a clear separation of responsibilities
A web page with structure, style,...
What is jQuery
•

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

•

HTML element selection and document obje...
History of jQuery
•

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

•

The L...
Adding JQuery
•

Local System
– Can add using <script> by downloading the minified version
– <script type="text/javascript...
Adding jQuery with Google CDN
•

Google has jQuery libraries on its Content delivery network and allows any
website to use...
The jQuery Function
•

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

•

Wraps the coll...
Document Ready Handler
•

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

•

This delays e...
First JQUERY-Anonymous Functions
<head>
<script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script type...
JQuery with Named Functions
<script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script type="text/javas...
2

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

Basic Selectors
Hierarchy Selectors
Selection By Attribute
Form Selectors
Position Filters
Oth...
Basic Selectors
•

Basic jQuery selectors work the same as CSS selectors:

•

$(“*”) - // Selectors return a pseudo-array ...
Basic Selectors
=$("#id1").text();
•

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

•

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

•

$(".style1").text();...
Controlling the context
•

$(“”, $())

•

First argument -> is a selector,

•

Second argument -> denotes the context of t...
Selection By Attribute
•

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

•

$('a[href=“Welcome.htm...
Working with DOM Attributes
•
•

jQuery can be used easily manipulate an element's attributes
Can be used to set and get a...
Applying Styles
•

The addClass( classes ) method can be used to apply defined
style sheets onto all the matched elements....
Hierarchy Selectors
•

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

:input -> Input, textarea, select, and button elements
:enabled -> Form elements that are enable...
Find Dropdown Selected Item
<select name=“cities”>
<select name=“cities”>
<option value=“1”>Chennai</option>
<option value...
Selecting by Position
•

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

•

p:odd
– This sel...
Position Selection

•
•

Can filter the elements selected based on their position in the
collection
$('.article:eq(2)');
–...
Other Selections
•

$(p:contains(‘java'));
– Selects all <p> elements that contain the string “java", either directly or
i...
jQuery Method Chaining
•

Selections return an instance of a jQuery object.

•

Returned instance can then invoke methods ...
Methods

•

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

Methods
.filter()
– Constructs a new jQuery object from a subset of the matching elements.
– The supplied selector is t...
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 j...
Css Manipulations
•
•

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

•

To Se...
Handling CSS Class
• To add and remove class
• $(“p”).removeClass(“blue”).addClass(“red”);
• To add if absent, remove othe...
3

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

DOM Traversal
Creating Elements
Inserting Elements
Inserting an Element Before or After Anot...
DOM Traversal
•

DOM Traversal can be done using the results of a selection

•

Can select the children, the parents, and ...
DOM Traversal
•

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

•

$('.menu-li2').pa...
Creating Elements
•

There are two ways to create elements in jQuery:

•

A string with HTML markup as argument to the jQu...
Inserting Elements
•

Create elements can be insert elements into a page.

•

Elements can be inserted:
–
–
–
–

•

Before...
Inserting an Element Before Another Element
•

.insertBefore()
– $(‘<ol><li>Chennai</li></ol>').insertBefore('#place_list1...
Inserting an Element as the Last Child of a Parent
•

.append() : As the Last Child
– newRow= "<tr><td>F105</td><td>jQuery...
Cloning (Copying) Elements
•
•
•

Copy of element can be done with .clone() method ,
creates a “deep copy” of an existing ...
Removing Elements
•

There are two methods remove a selection: .detach() and.remove().
– both return the removed selection...
Deleting Elements
•
•

empty() : will remove all the contents of the selection.
remove() : will remove the selection and i...
Replacing Elements
•

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

•

.replaceWith()
– Replace each element ...
5

EVENT HANDLING
Topics
•

Events Overview

•

Binding An Event Handler

•

Binding Shortcut Methods

•

Unbinding Handlers and “One-Shot” ...
Event Handling
•
•
•

The event handling methods are core functions in jQuery.
Event handlers are method that are called w...
JQuery Events
•

$(document).ready(function)
–

•

$(selector).click(function)
–

•

Triggers, or binds a function to the ...
Event Handling
function makeUpperCase()
{
$(this).val($(this).val().toUpperCase());
}
$(document).ready(function(){
$("#up...
Basic Syntax of Event Binding
• .bind( eventType [, eventData ], handler(eventObject) )
•

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

Attaching a handler to multiple events

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

event.target
– ref to element triggering event

•

event.target.id
– id of element triggering event
...
Event Data
$("#img1").bind('click.ns1',{name: 'ramesh'},function(event){
if(event.data.name==='ram')
{
$("#img1").toggleCl...
Event Name spacing
•

Can add a event within a specific namespace and then remove that
events from that namespace.
$("#img...
Event Bubbling
•

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

•

It handled by the event handler

•

It also...
Event Handling Methods
•

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

•

stopPropagation()
– ...
Event Bubbling
$( 'h1,a' ).on( 'click', function( event ) {
event. stopPropagation();
alert( $( this ).attr( 'id' ) ); }
<...
Preventing the default action
•

preventDefault()
– Called on the event object, used to prevent the default action of an
e...
Live() Method
•

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

•

Live even...
die() Method
•

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

•

This method is analogous...
On Method
•

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

•

Introduced with jQuery 1.7,

•

Its combinati...
On Method
$(function(){
$(document.body).on('mouseover',"#tab tr", function(){
$(this).addClass("selected");
}) .on('mouse...
Triggering Events
•

trigger( eventType, data )
– Execute all handlers and behaviors attached to the matched elements
for ...
Creating Custom Events
•

Can Create our own custom events using jQuery event binder
Methods

•

Done by providing event b...
Creating Custom Events
$(function(){
$("p").on("myCustomEvent", function(event,d){
alert("event"+ event.type + "data"+ d.n...
ContextMenu - Event
•

The contextmenu event is fired when the right button of the mouse
is clicked before the context men...
EFFECTS AND ANIMATIONS
Showing and hiding elements
•

Showing or hiding elements are simple and pop elements into
existence or make them instantl...
Useful Functions
•
•
•
•

.hide()
– display:none
.show()
– display:true
.toggle(func1, func2)
– first click calls func1, n...
Useful Functions
•
•

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

•

.toggle(fun...
Fading Elements
•

fadeIn(speed,callback)
– Causes any matched elements that are hidden to be shown by
gradually changing ...
Fading Elements
•

fadeOut(speed,callback)
– Causes any matched elements that aren’t hidden to be removed from
the display...
Fading Elements
•

fadeTo(speed,opacity,callback)

•

Doesn’t remember the original opacity of an element.

•

Used to exp...
Sliding Elements Up and down
•

Similar manner to the hide() and show() effects, except that the elements
appear to slide ...
Sliding Elements
$(“div”).slideUp();
$(“div”).slideUp();
$(“div”).slideDown(“fast”);
$(“div”).slideDown(“fast”);
$(“div”)....
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() wrap...
Animate
$("#out").click(function(){
$("#block").animate({
width: "70%",
opacity: 0.4,
marginLeft: "0.6in",
fontSize: "3em"...
Chaining Animation

$(“div”).animate({width: “90%”},100)
$(“div”).animate({width: “90%”},100)
.animate({opacity: 0.5},200)...
Controlling Animations Sync
$(“div”)
$(“div”)
.animate({width: “90%”},
.animate({width: “90%”},
{queue:false, duration:100...
Stopping Animations
•

stop(clearQueue,gotoEnd)
– Halts any animations that are currently in progress for the elements in
...
JQUERY –AJAX INTERACTION
Ajax Interaction
XMLHttpRequest
•

JavaScript object

•

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

•

Communicates...
Server-Side AJAX Request Processing
•

Server programming model remains the same
– It receives standard HTTP GETs/POSTs
– ...
Ajax with jQuery
•

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

•

$.get...
Load Method
•
•
•

•
•

•

This method is called on a selection ,
Fetches the HTML from a URL and uses the returned HTML t...
$.ajax()
•

Powerful and straightforward way of creating ajax request

•

It takes an configuration object that has the al...
Making an Ajax Call
$(document).ready(function(){
$("button").click(function(){
$.ajax({url:"First.Jsp", success:function(...
Get and Post Method
•
•
•

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

•

jQuery.post( url [,...
$.ajax()
•

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

type: 'GET',
url: ‘ProcessData.jsp',
dataType: 'ht...
Load Java Script
Show.js
function show()
{
data =new Array("Head First Java","Spring in Action","thinking in Java");
}

va...
JQuery AJAX Events:
•
•
•
•

•
•
•

•

The methods used during the life cycle of AJAX call progress.
Based on different ev...
Ajax Global Events
•

Events that are broadcast to all elements in the DOM, triggering any
handlers which may be listening...
Local Events
•

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

The jqXHR.success(), jqXHR.error(), jqXHR.complete() callbacks
are deprecated as of jQuery...
Example
var jqxhr = $.ajax( "example.jsp" ).done(function() {
alert("success"); })
.fail(function() { alert("error"); })
....
JSON: JavaScript Object Notation.
•
•
•
•
•

Lightweight text-data interchange format
"self-describing" and easy to unders...
JSON Syntax Rules
•

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

Data is in name/value pair...
Working With Json Data
•

Servers return JSON string against a request.

•

getJSON() parses the returned JSON string and ...
Generating JSON Data
User user = new User(101,”Ramesh);
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValue(...
Working With Json Data
$(document).ready(function() {
$("#driver").click(function(event){ $.getJSON('user.json', function(...
Ajax with JSON Data
$.ajax({
type: "GET",
cache: false,
contentType: "application/json; charset=utf-8",
url: 'JsonResponse...
JQUERY-UI
jQuery UI - Overview
•

Provides abstractions for low-level interaction and animation, advanced effects
and high-level, th...
UI Library
•

Jquery has various Widgets using UI Libraries

•

Required Libraries are downloaded and added to the pages

...
UI Library Based Effects:
•

Call effect on any DOM element

•

.effect(effect,[options],[speed],[callback]}
o speed
 "sl...
UI Library Based Effects
•
•

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

...
Draggable
•

Make the selected elements draggable by mouse.

•

Can also drag& drop, Using Droppable plugin, which provide...
Draggable
$(function() {
$( "#draggable" ).draggable();
});
</script>
</head>
<body>
<div id="draggable" class="ui-widget-...
Droppable
•

Makes selected elements droppable

•

They accept being dropped on by draggables.

•

Can specify which dragg...
Droppable
$(function() {
$(".square").draggable();
$(".squaredotted").droppable({
drop : function(event, ui) {
$("#info")....
Droppable- Accept
$(".square").draggable();
$("#serverSideScript").droppable({
accept : "#jsp",
drop : function(event, ui)...
Resizeable
•

The jQuery UI Resizable plugin makes selected elements resizable

•

Has a draggable resize handles

•

Can ...
Buttons
•

Enhances standard form elements like buttons, inputs and anchors
to themeable buttons with appropriate hover an...
Date Picker
Date Picker
•

Used in textfield to pop up calendar.

•

Choosing day from calendar puts date string into textfield

•

HT...
Date Picker
<form action=#">
From: <input type="text"/>
Departure Date: <input type="text" id="start-date"/>
Return Date: ...
Main Option of DatePicker
•

$(function() {
$("#bDate").datepicker({buttonImage: "../images/calendar.gif",
buttonImageOnly...
Accordian
Accordion Panel

•

Horizontally stacked panels with wide tabs

•

HTML
– Need container to hold the tabs

•

Create alter...
Accordian
<script>
$(document).ready(function() {
$(“#accrd ").accordion();
});
</script>
•

$("#accrd1").accordion({event...
Tab Panel
Tabbed Panel
•
•

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

•
•

<d...
Tab Panel
<script>
$(document).ready(function() {
$("#tabs").tabs();
});
</script>
<div id="tabs">
<ul>
<li><a href="#frag...
Tab- Options
•

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

Autocomplete enables users to quickly find and select from a prepopulated list of values as they type, lev...
AutoComplete
$(function() {
var scripts= ["JavaScript“,"Lisp“,"Ruby“, "Scala“, "Scheme” ];
$( "#tags" ).autocomplete({sour...
Dialog
•
•

A way delivering information to the user.
Created by Selecting the content to become the body and the dialog()...
Dialog
•
•
•
•
•

$("#diaMsg").dialog({modal: false,buttons:{
Ok:function(){$(this).dialog("close");
$("#diaAnch1").hide()...
Creating Menu
•

Can create Menu with mouse and keyboard interactions for
navigation.

•

Created from any valid markup th...
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.

$( "#sli...
EXTENDING JQUERY
Plugin
•

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

•

Plugin works with a collection of elements
...
Create a basic Plugin
•

The recommended guideline
– Prefix the filename with jquery.
– Follow that with the name of the p...
Developing a Plug-in -Function
( function($){

$.fn.makeItBlue = function() {
return this.css('color','blue');
};
})(jQuer...
Contained Function
•

The code to run plugin can be contained within a function

•

Used for writing a plugin that acts up...
Assoicating Function with Global Name space
(function($){
$.sum = function(array) {
var total = 0;
$.each(array, function(...
Using the Global Namespace
$(document).ready(function() {
var $inventory = $('#inv');
var quantities = $inventory.find('td...
$.extend()
•

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

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

•

To add a more than one plugin methods to ...
Parameter Passing –Using Extend
(function($){
$.fn.selColor = function(opts) {
var defaults = {color:'red'};
var $original...
Parameter Passing
(function($) {
$.fn.shadow = function(opts) {
var defaults = {
copies: 5,
opacity: 0.1,
copyOffset: func...
Parameter Passing
for (var i = 0; i < opts.copies; i++) {
var offset = options.copyOffset(i);
$originalElement
.clone()
.c...
Plugin

WIDGET FACTORY
Need for Widget Factory
•

The plugin becomes "stateful,“
– can examine, alter, or even completely reverse the effects of ...
Using Widget Factory
•

Used
– To create a plugin to create a new user interface element,
– To extend the jQuery UI librar...
Creating Widget
•

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

•

It accepts the name of th...
Creating Widgets
•

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

•

First argument...
Invoking Widgets
•

$(“div").simpler();
– Widget method is used as the primary interface to the widget,
– Called when init...
Life cycle Functions in widgets
•

_create()
–
–
–
–
–

•

_init()
–
–
–
–

•

Invoked the first time the widget is applie...
Working with Widget Options
•

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

var m...
Widgets with options
$.widget("com.simpler",{
options: {
msg :"Welcome to Widget Creations",
prefClass:"style1"
},
_create...
Adding Methods to a Widget
•

Public Functions can be defined in the Plugin

•

Defined in the jQuery.widget();

•

Can de...
Widget with Public functions

options: {
msg :"Welcome to Widget Creations",
prefClass:"style1” },
_create:function(){
var...
Widget with Private functions
showColor:function(cls)
{
if(cls===undefined) {
return this.options.prefClass;
}
else {
this...
Qunit
•

Developed by John Resig as part of jQuery.

•

QUnit runs completely standalone.
<link rel="stylesheet" href="/re...
Test With truthy
•

<script>
test( "a basic test example", function() {
var value = $("div[id^='d']").size() % 2 ===0 ;
ok...
Test For Equal
•

<script>

•
•

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

•
•

eq...
Download This presentation

http://sdrv.ms/1erDF7B
J query module1
J query module1
Upcoming SlideShare
Loading in...5
×

J query module1

747

Published on

Published in: Education, Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
747
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
12
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • 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.
  • 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.
  • J query module1

    1. 1. K.Srivatsan • • • IT Trainer Since 1991 Conducting Java Training Since 2004 About 40+ Corporate Clients
    2. 2. 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
    3. 3. 1 INTRODUCTION TO JQUERY
    4. 4. Topics • Motivation for jQuery • History Of jQuery • What is jQuery • jQuery vs Custom JavaScript • jQuery vs Other JavaScript Libraries • Quick Start jQuery
    5. 5. 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.
    6. 6. 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.
    7. 7. 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.
    8. 8. 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
    9. 9. 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
    10. 10. 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.
    11. 11. 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
    12. 12. 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()); });
    13. 13. 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>
    14. 14. 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"/>
    15. 15. 2 SELECTION AND DOM TRAVERSAL
    16. 16. Topics • • • • • • • • • • Basic Selectors Hierarchy Selectors Selection By Attribute Form Selectors Position Filters Other Filters Method Chaining DOM Traversal Filter Methods Advanced Method Chaining
    17. 17. 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
    18. 18. Basic Selectors =$("#id1").text(); • <p id="id1">Java</p> • <p id="id2" class="style1">JEE</p> • $(".style1").text(); <div>Spring</div> =$(“div“).text();
    19. 19. 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
    20. 20. 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
    21. 21. 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");
    22. 22. 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.
    23. 23. 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.
    24. 24. 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();
    25. 25. 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()
    26. 26. 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
    27. 27. 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.
    28. 28. 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
    29. 29. 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.
    30. 30. 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); });
    31. 31. • 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
    32. 32. 4 CSS STYLING AND JQUERY
    33. 33. 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")
    34. 34. 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” } • );
    35. 35. 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”)) { //… }
    36. 36. 3 DOM AND ATTRIBUTE MANIPULATION
    37. 37. 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
    38. 38. 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.
    39. 39. 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.
    40. 40. 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' });
    41. 41. 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)
    42. 42. 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.
    43. 43. 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");
    44. 44. 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);
    45. 45. 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.
    46. 46. 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>" //
    47. 47. 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”);
    48. 48. 5 EVENT HANDLING
    49. 49. 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()
    50. 50. 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>
    51. 51. 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
    52. 52. Event Handling function makeUpperCase() { $(this).val($(this).val().toUpperCase()); } $(document).ready(function(){ $("#uppercase-field").keyup(makeUpperCase); }); <input type="text" name="userName" id="uppercase-field">
    53. 53. 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());
    54. 54. Bind multiple events simultaneously. $("div.test").bind({ click: function(){ $(this).addClass("active"); }, mouseenter: function(){ $(this).addClass("inside"); }, mouseleave: function(){ $(this).removeClass("inside"); } });
    55. 55. Many Events & Handler • Attaching a handler to multiple events function handler(e){ alert('event'); } $('div').click(handler) .keydown(handler);
    56. 56. ‘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 • •
    57. 57. Event Data $("#img1").bind('click.ns1',{name: 'ramesh'},function(event){ if(event.data.name==='ram') { $("#img1").toggleClass("class1"); } else { $("#img1").toggleClass("class2"); } });
    58. 58. 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); });
    59. 59. 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.
    60. 60. 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.
    61. 61. 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
    62. 62. 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!' ); });
    63. 63. 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'); }); });
    64. 64. 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..."); });
    65. 65. 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 ) {} );
    66. 66. 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>'); }); });
    67. 67. 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"); }));
    68. 68. 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.
    69. 69. 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'}); }); });
    70. 70. 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; });
    71. 71. EFFECTS AND ANIMATIONS
    72. 72. 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.
    73. 73. Useful Functions • • • • .hide() – display:none .show() – display:true .toggle(func1, func2) – first click calls func1, next click executes func2 .hover(over, out) – mouseover, mouseout
    74. 74. 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
    75. 75. 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); }); });
    76. 76. 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); }); });
    77. 77. 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); }); });
    78. 78. 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. •
    79. 79. Sliding Elements $(“div”).slideUp(); $(“div”).slideUp(); $(“div”).slideDown(“fast”); $(“div”).slideDown(“fast”); $(“div”).slideToggle(1000); $(“div”).slideToggle(1000);
    80. 80. Reset Predefined Spees – jQuery.fx.speeds.fast = 50; • Create a new pre-defined speed – jQuery.fx.speeds.turtle = 3000;
    81. 81. 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.
    82. 82. Animate $("#out").click(function(){ $("#block").animate({ width: "70%", opacity: 0.4, marginLeft: "0.6in", fontSize: "3em", borderWidth: "10px" }, 1500 ); });
    83. 83. 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
    84. 84. 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
    85. 85. 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).
    86. 86. JQUERY –AJAX INTERACTION
    87. 87. Ajax Interaction
    88. 88. 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
    89. 89. 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
    90. 90. 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.
    91. 91. 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);
    92. 92. $.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
    93. 93. 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>
    94. 94. 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());
    95. 95. $.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 );
    96. 96. 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); });
    97. 97. 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.
    98. 98. 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, });
    99. 99. Local Events • These are callbacks that you can subscribe to within the Ajax request object $.ajax({ beforeSend: function(){ }, complete: function(){ } });
    100. 100. 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
    101. 101. Example var jqxhr = $.ajax( "example.jsp" ).done(function() { alert("success"); }) .fail(function() { alert("error"); }) .always(function() { alert("complete"); });
    102. 102. 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).
    103. 103. 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"
    104. 104. 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.
    105. 105. 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(); }
    106. 106. 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" />
    107. 107. 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); } }); }
    108. 108. JQUERY-UI
    109. 109. 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
    110. 110. 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
    111. 111. 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
    112. 112. 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"); }); }); });
    113. 113. 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" });
    114. 114. Draggable $(function() { $( "#draggable" ).draggable(); }); </script> </head> <body> <div id="draggable" class="ui-widget-content"> <p>Using Drags</p> </div>
    115. 115. 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 " });
    116. 116. 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!"); } }); });
    117. 117. 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>
    118. 118. 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'}); });
    119. 119. 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" });
    120. 120. Date Picker
    121. 121. 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();
    122. 122. 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 }); });
    123. 123. 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.
    124. 124. Accordian
    125. 125. 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();
    126. 126. 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});
    127. 127. Tab Panel
    128. 128. 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();
    129. 129. 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>
    130. 130. 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" });
    131. 131. 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 });
    132. 132. 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>
    133. 133. 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(); });
    134. 134. 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.
    135. 135. 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>
    136. 136. Menu • $( ".selector" ).menu({ disabled: true }); • $( ".selector" ).menu({ icons: { submenu: "ui-icon-circle-trianglee" } });
    137. 137. 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 ] ); } });
    138. 138. EXTENDING JQUERY
    139. 139. 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)
    140. 140. 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
    141. 141. Developing a Plug-in -Function ( function($){ $.fn.makeItBlue = function() { return this.css('color','blue'); }; })(jQuery); Invoking the plugins $("#p1").makeItBlue();
    142. 142. 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);
    143. 143. 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);
    144. 144. 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); });
    145. 145. $.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.
    146. 146. 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 }); } });
    147. 147. 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);
    148. 148. 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);
    149. 149. 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);
    150. 150. Plugin WIDGET FACTORY
    151. 151. 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,
    152. 152. 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.
    153. 153. 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.
    154. 154. 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.
    155. 155. 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.
    156. 156. 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
    157. 157. 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.
    158. 158. 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();
    159. 159. 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.
    160. 160. 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");
    161. 161. 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; } } },
    162. 162. 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>
    163. 163. 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>
    164. 164. 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>
    165. 165. Download This presentation http://sdrv.ms/1erDF7B
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×