J query module1

167

Transcript of J query module1

Page 1: J query module1
Page 2: J query module1

K.Srivatsan• IT Trainer Since 1991

• Conducting Java Training Since 2004

• About 40+ Corporate Clients

Page 3: J query module1

Agenda1. Introduction to jQuery

2. Selection and DOM Traversal

3. DOM and Attribute Manipulation

4. CSS Styling and jQuery

5. Event Handling with jQuery

6. Effects and Custom Animations

7. Ajax Calls with jQuery

8. jQuery UI

9. Plugin Development with jQuery

Page 4: J query module1

INTRODUCTION TO JQUERY1

Page 5: J query module1

Topics

• Motivation for jQuery

• History Of jQuery

• What is jQuery

• jQuery vs Custom JavaScript

• jQuery vs Other JavaScript Libraries

• Quick Start jQuery 

Page 6: J query module1

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.

Page 7: J query module1

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.

Page 8: J query module1

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.

Page 9: J query module1

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

Page 10: J query module1

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

Page 11: J query module1

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.

Page 12: J query module1

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

Page 13: J query module1

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());

});

Page 14: J query module1
Page 15: J query module1

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>

Page 16: J query module1

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"/>

Page 17: J query module1

SELECTION AND DOM TRAVERSAL

2

Page 18: J query module1

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

Page 19: J query module1

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

Page 20: J query module1

Basic Selectors

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

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

• <div>Spring</div>

=$("#id1").text();

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

=$(“div“).text();

Page 21: J query module1

Controlling the context• $(“”, $()) -> function can have a second argument

• 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");

Context of Selection

Element to Selection

Page 22: J query module1

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

Page 23: J query module1

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");

Page 24: J query module1

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.

Page 25: J query module1

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.

Page 26: J query module1

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();

Page 27: J query module1

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

Find Dropdown Selected Item

<select name=“cities”>

<option value=“1”>Chennai</option>

<option value=“2”>Trichy</option>

<option value=“3”>Madurai</option>

</select>

<select name=“cities”>

<option value=“1”>Chennai</option>

<option value=“2”>Trichy</option>

<option value=“3”>Madurai</option>

</select>

Page 28: J query module1

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

Page 29: J query module1

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.

Page 30: J query module1

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

Page 31: J query module1

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.

Page 32: J query module1

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);

});

Page 33: J query module1

  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

Page 34: J query module1

CSS STYLING AND JQUERY4

Page 35: J query module1

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")

Page 36: J query module1

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”

}

• );

Page 37: J query module1

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”)) { //… }

Page 38: J query module1

DOM AND ATTRIBUTE MANIPULATION

3

Page 39: J query module1

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

Page 40: J query module1

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.

Page 41: J query module1

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.

Page 42: J query module1

 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' });

Page 43: J query module1

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)

Page 44: J query module1

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.

Page 45: J query module1

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");

Page 46: J query module1

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);

Page 47: J query module1

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.

Page 48: J query module1

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(); // --> "<div><p></p></div>" //

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

Page 49: J query module1

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”);

Page 50: J query module1

EVENT HANDLING5

Page 51: J query module1

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()

Page 52: J query module1

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>

Page 53: J query module1

JQuery Events• $(document).ready(function)  

– Binds a function to the ready event of a document

• $(selector).click(function) – Triggers, or binds a function to the click event of selected elements

• $(selector).focus(function) – 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

Page 54: J query module1

Event Handling

function makeUpperCase()

{

$(this).val($(this).val().toUpperCase());

}

$(document).ready(function(){

$("#uppercase-field").keyup(makeUpperCase);

});

<input type="text" name="userName" id="uppercase-field">

Page 55: J query module1

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());

Page 56: J query module1

Bind multiple events simultaneously.

$("div.test").bind({

click: function(){

$(this).addClass("active");

},

mouseenter: function(){

$(this).addClass("inside");

},

mouseleave: function(){

$(this).removeClass("inside");

}

});

Page 57: J query module1

Many Events & Handler

• Attaching a handler to multiple events

function handler(e){

alert('event');

}

$('div').click(handler)

.keydown(handler);

Page 58: J query module1

‘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

Page 59: J query module1

Event Data $("#img1").bind('click.ns1',{name: 'ramesh'},function(event){

if(event.data.name==='ram')

{

$("#img1").toggleClass("class1");

}

else

{

$("#img1").toggleClass("class2");

}

});

Page 60: J query module1

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);

});

Page 61: J query module1

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.

Page 62: J query module1

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.

Page 63: J query module1

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

Page 64: J query module1

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!' );

});

Page 65: J query module1

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'); });• });

Page 66: J query module1

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...");

});

Page 67: J query module1

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 ) {} );

 

Page 68: J query module1

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>');

});

});

Page 69: J query module1

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");   }));

Page 70: J query module1

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.

Page 71: J query module1

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'});

});

});

Page 72: J query module1

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;

});

Page 73: J query module1

EFFECTS AND ANIMATIONS

Page 74: J query module1

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.

Page 75: J query module1

Useful Functions

• .hide()– display:none

• .show()– display:true

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

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

Page 76: J query module1

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

Page 77: J query module1

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);

});

});

Page 78: J query module1

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);

});

});

Page 79: J query module1

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);

});

});

Page 80: J query module1

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.

Page 81: J query module1

$(“div”).slideUp();

$(“div”).slideDown(“fast”);

$(“div”).slideToggle(1000);

$(“div”).slideUp();

$(“div”).slideDown(“fast”);

$(“div”).slideToggle(1000);

Sliding Elements

Page 82: J query module1

Reset Predefined Spees

– jQuery.fx.speeds.fast = 50;

• Create a new pre-defined speed

– jQuery.fx.speeds.turtle = 3000;

Page 83: J query module1

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: – A map of CSS properties that the animation will move toward.

• duration: – This is optional parameter representing how long the animation will run.

• easing: ( linear and swing)– 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.

Page 84: J query module1

Animate

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

$("#block").animate({

width: "70%",

opacity: 0.4,

marginLeft: "0.6in",

fontSize: "3em",

borderWidth: "10px"

}, 1500 );

});

Page 85: J query module1

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

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

Chaining Animation

By default animations are queued and than performed one by one

Page 86: J query module1

$(“div”).animate({width: “90%”},

{queue:false, duration:1000}).animate({opacity : 0.5});

$(“div”).animate({width: “90%”},

{queue:false, duration:1000}).animate({opacity : 0.5});

Controlling Animations Sync

The first animation will be performed immediately without queuing

Page 87: J query module1

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).

Page 88: J query module1

JQUERY –AJAX INTERACTION

Page 89: J query module1

Ajax Interaction

Page 90: J query module1

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

Page 91: J query module1

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

Page 92: J query module1

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.

Page 93: J query module1

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);

Page 94: J query module1

$.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

Page 95: J query module1

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>

Page 96: J query module1

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());

Page 97: J query module1

$.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 );

Page 98: J query module1

Load Java ScriptShow.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);

});

Page 99: J query module1

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.

Page 100: J query module1

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,

});

Page 101: J query module1

Local Events• These are callbacks that you can subscribe to within the Ajax

request object

$.ajax({

beforeSend: function(){

},

complete: function(){

}

});

Page 102: J query module1

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

Page 103: J query module1

Example

var jqxhr = $.ajax( "example.jsp" ).done(function() {

alert("success"); })

.fail(function() { alert("error"); })

.always(function() { alert("complete"); });

Page 104: J query module1

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).

Page 105: J query module1

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"

Page 106: J query module1

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.

Page 107: J query module1

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();

}

Page 108: J query module1

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" />

Page 109: J query module1

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);

}

});

}

Page 110: J query module1

JQUERY-UI

Page 111: J query module1

    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

Page 112: J query module1

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

Page 113: J query module1

UI Library Based Effects:• Call effect on any DOM element 

• .effect(effect,[options],[speed],[callback]}o speed

 "slow", "normal", or "fast" or # of millisecondso 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

Page 114: J query module1

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");• });

• });• });

Page 115: J query module1

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" });

Page 116: J query module1

Draggable

$(function() {

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

});

</script>

</head>

<body>

<div id="draggable" class="ui-widget-content">

<p>Using Drags</p>

</div>

Page 117: J query module1

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 " });

Page 118: J query module1

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!");

}

});

});

Page 119: J query module1

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>

Page 120: J query module1

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'});

});

Page 121: J query module1

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" });

Page 122: J query module1

   Date Picker  

Page 123: J query module1

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();

Page 124: J query module1

   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 });

});

Page 125: J query module1

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.

Page 126: J query module1

Accordian

Page 127: J query module1

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();

Page 128: J query module1

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});

Page 129: J query module1

Tab Panel

Page 130: J query module1

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();

Page 131: J query module1

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>

Page 132: J query module1

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" });

Page 133: J query module1

AutoComplete• Autocomplete enables users to quickly find and select from a pre-

populated 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

});

Page 134: J query module1

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>

Page 135: J query module1

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(); });

Page 136: J query module1

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.

Page 137: J query module1

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>

Page 138: J query module1

Menu

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

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

Page 139: J query module1

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 ] );

} });

Page 140: J query module1

EXTENDING JQUERY

Page 141: J query module1

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)

Page 142: J query module1

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

Page 143: J query module1

Developing a Plug-in -Function

( function($){

$.fn.makeItBlue = function() {

return this.css('color','blue');

};

})(jQuery);

Invoking the plugins

$("#p1").makeItBlue();

Page 144: J query module1

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);

Page 145: J query module1

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);

Page 146: J query module1

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);

});

Page 147: J query module1

$.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.

Page 148: J query module1

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

});

}

});

Page 149: J query module1

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);

Page 150: J query module1

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);

Page 151: J query module1

Parameter Passingfor (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);

Page 152: J query module1

WIDGET FACTORYPlugin

Page 153: J query module1

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,

Page 154: J query module1

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.

Page 155: J query module1

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.

Page 156: J query module1

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.

Page 157: J query module1

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.

Page 158: J query module1

Life cycle Functions in widgets• _create()

– 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

• _init()– 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

Page 159: J query module1

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.

Page 160: J query module1

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();

Page 161: J query module1

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.

Page 162: J query module1

Widget with Public functionsoptions: {

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");

Page 163: J query module1

Widget with Private functionsshowColor: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; }

Page 164: J query module1

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>

Page 165: J query module1

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>

Page 166: J query module1

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>

Page 167: J query module1

Download This presentation

http://sdrv.ms/1erDF7B