Web Development using jQuery

81
RJUG: 10-April-2012 Bryan Basham – Web Development using jQuery Slide 1 © Copyright 2012, Software Alchemy JavaScript Frameworks jQuery Event Model Querying the DOM Manipulating the DOM Ajax Event Queue Using Plugins Web Development using jQuery Bryan Basham Software Alchemy [email protected] http://www.linkedin.com/in/SoftwareAlchemist

Transcript of Web Development using jQuery

Page 1: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 1

© Copyright 2012, Software Alchemy

JavaScriptFrameworks

jQueryEventModel

Queryingthe DOM

Manipulatingthe DOMAjax

EventQueue

UsingPlugins

Web Development using jQuery

Bryan BashamSoftware Alchemy

[email protected]

http://www.linkedin.com/in/SoftwareAlchemist

Page 2: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 2

© Copyright 2012, Software Alchemy

Assumptions

● This talk assumes basic understanding of:– HTML– CSS– Core JavaScript syntax– Functional programming principles

● See SlideShare: Introduction to JavaScript

Page 3: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 3

© Copyright 2012, Software Alchemy

Wars& Warts

Low-levelframeworks High-level

frameworks

UsingPlugins

Queryingthe DOM

EventModel

Manipulatingthe DOM

DEMO #1

JavaScriptFrameworks

Ajax

EventQueue

jQuery

JavaScript Frameworks

Page 4: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 4

© Copyright 2012, Software Alchemy

Wars and Warts

● Browser wars of the bad old days● Uneven support for DOM standards● Quirks and bugs of older browsers● Supporting multiple browsers is tricky

– Esp. multiple versions of IE

Page 5: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 5

© Copyright 2012, Software Alchemy

JavaScript Frameworks

● Dozens of frameworks grew out of the need to build user-friendly and advanced webapps

● Wide variety of techniques:– Modification of standard APIs: eg, Prototype– Functional wrappers: eg, jQuery– Object-Oriented class library: eg, ExtJS

● Best to select one library but it's possible to use two or more together

– Beware of namespace conflicts, esp the $ function (Prototype and jQuery)

Page 6: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 6

© Copyright 2012, Software Alchemy

Low-level Frameworks

● Low-level frameworks provide:– Cross-browser compatibility– Advanced DOM APIs: query, traversal,

manipulation, and so on– Advanced Ajax APIs

● Examples:– Prototype– jQuery– Dojo (core modules)

● Frequently extensible using plugins

Page 7: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 7

© Copyright 2012, Software Alchemy

High-level Frameworks

● High-level frameworks provide:– UI Widgets– UI Layout tools– UI Effects

● Examples:– Script-aculo-us (w/ Prototype, but minimal)– jQuery UI (w/ jQuery, but minimal)– Dijit (v1.7) (Dojo's widget library, more and

modular)– ExtJS (all-in-one; lots of widgets, layouts, etc)

Page 8: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 8

© Copyright 2012, Software Alchemy

jQuery

● jQuery development starts with building event handlers for specific elements.

● Principles:– Implicit iteration (Wikipedia)

$('SELECTOR').method(...);// sort of like this:$('SELECTOR').each(function (idx, element) { method.call(element, ...);});

– Method chaining (Wikipedia)$('SELECTOR').action1(...).action2(...).action3(...);// sometimes written like this:$('SELECTOR').action1(...).action2(...).action3(...);

Page 9: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 9

© Copyright 2012, Software Alchemy

Demo #1: View an Exam

● This first demo shows several simple effects and event handlers.

● The demo came from a webapp original built for Sun Microsystems, certification team:

Page 10: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 10

© Copyright 2012, Software Alchemy

Wars& Warts

Low-levelframeworks High-level

frameworks

UsingPlugins

EventModel

Manipulatingthe DOM

DEMO #1

JavaScriptFrameworks

Ajax

EventQueue

jQuery

Standard APIsjQuery Selectors

Std Traversal

jQuery Traversal

Queryingthe DOM

Querying the DOM

Page 11: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 11

© Copyright 2012, Software Alchemy

Node

Document Element CharacterData

Text Comment

CDATASection

1

childNodes

parentNode 10..*

0..*

The relationship between the Element andthe abstract CharacterData type is implied bythe Node's ability to contain children of anyNode subtype, such as Text or Comment.

documentElement{AKA: the root node}

Standard DOM Type Hierarchy

Page 12: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 12

© Copyright 2012, Software Alchemy

Document Example<html><head></head><body> <div id="login"> <form action="" id="login_form"> <fieldset> <ol> <li> <label for="login_id"> Login <abbr title="identification">ID</abbr> </label> <input id="login_id" name="username" type="text" /> </li> <li> <label for="password">Password</label> <input id="password" name="userpass" type="password" /> <a href="#">go</a> </li> </ol> </fieldset> </form> </div></body></html>

Page 13: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 13

© Copyright 2012, Software Alchemy

DOM Example

<HTML>

<HEAD> <BODY>

<DIV>

<FORM>

<OL>

<LI>

<FIELDSET>

<LABEL>

<LI>

<INPUT “username”> <LABEL> <A><INPUT “userpass”>

Page 14: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 14

© Copyright 2012, Software Alchemy

Standard DOM Query APIs

Document

getElementById(elementId) : ElementgetElementsByTagName(tagName) : NodeList

Element

tagName : DOMString

getElementsByTagName(tagName) : NodeListgetElementsByClassName(clsName) : NodeList

Node

1

documentElement{AKA: the root node}

NodeList

length : long

[idx] : Nodeitem(idx) : Node

Page 15: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 15

© Copyright 2012, Software Alchemy

Using the DOM Query APIs

● Find the unique element by its id// retrieves the <form> element with id of 'login_form'var myForm = document.getElementById('login_form');

● Find a list of elements by tag type– Search the whole document:

// retrieves all <input> elements in the whole documentdocument.getElementsByTagName('input');

– Search down from a specific element:// retrieves all <input> elements in <form id='login_form'>...</form>myForm.getElementsByTagName('input');

● Find a list of elements with a specific class:myForm.getElementsByClassName('form_error');

Page 16: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 16

© Copyright 2012, Software Alchemy

jQuery Selector Function

● The standard APIs are limited so frameworks provide more flexible querying APIs

● jQuery allows querying for DOM elements using CSS selector syntax

– $('#nav_bar') – select unique element– $('td') – select all table data cells– $('div.section_head') – all divs of a class– $('table#myGrid th') – all heading cells

within a specific table – and much much more...

Page 17: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 17

© Copyright 2012, Software Alchemy

jQuery Selector Function

● The $ function always returns an array (possibly empty) of DOM elements

● It returns is a quasi-array, the jQuery object● It has powerful implicit iteration functions

– Execute arbitrary code:$('div.section_head').each(function(idx, element) { /* ... */ });

– Assign event handlers:$('a#collapse_all_sections').click(function(event) { $('ol#section_list > li ol').slideUp('slow'); event.preventDefault();});

– Manipulate the DOM:$('div.section_head').addClass('hightlighted');

Page 18: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 18

© Copyright 2012, Software Alchemy

jQuery Selector Function● Wrap a DOM element using the $ function:

– Wrap the window object:$(window).resize(function(event) { var $ctrPanel = $('#control_panel'); // common naming convention: $var var frame = $('#frame')[0]; // extract the actual DOM element object from the array $ctrPanel.css('left', (frame.offsetWidth+ frame.offsetLeft- $ctrPanel[0].offsetWidth)+ 'px');});

– Wrap the document object:(function($) { $(document).ready(function() { // execute this function when the DOM is ready Screen.initialise(); });})(jQuery);

– Wrap the target of an event handler:$('ol#section_list li').dblclick(function(event) { var $objectivesList = $(this).find('ol'); // wrap DOM element to get jQuery functionality if ($objectivesList.is(':visible')) { $objectivesList.fadeOut(2000); } else { $objectivesList.fadeIn(2000); }});

Page 19: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 19

© Copyright 2012, Software Alchemy

jQuery Selector Function

● The jQuery object is the heart of the jQuery library

● We have only scratched the surface:– Event handler registration– DOM manipulation– UI effects, such as hide, fading, sliding– Plugin enhancements

● Next, let's look at a related topic:DOM traversal

Page 20: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 20

© Copyright 2012, Software Alchemy

Standard DOM Traversal API

● The Node provides the traversal access:

Node

parentNode : NodechildNodes : NodeListfirstChild : NodelastChild : NodepreviousSibling : NodenextSibling : Node

hasChildNodes() : boolean

1

0..*

childNodes

parentNode

Page 21: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 21

© Copyright 2012, Software Alchemy

Traversal Example

LI:Element

LABEL:Element INPUT:Element A:Element

"password":Text "go":Text

parentNode

firstC

hild lastChild

nextSibling

previousSibling

<li> <label for="password">Password</label> <input id="password" name="userpass" type="password" /> <a href="#">go</a></li>

Page 22: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 22

© Copyright 2012, Software Alchemy

Traversal Example (reality check)<li> <label for="password">Password</label> <input id="password" name="userpass" type="password" /> <a href="#">go</a></li>

LI:Element

LABEL:Element INPUT:Element A:Element

"Password":Text "go":Text

firstChild lastChild

ws:Text ws:Text ws:Text ws:Text

Page 23: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 23

© Copyright 2012, Software Alchemy

jQuery Traversal APIs

● The basic jQuery traversal methods ignore text nodes; just gives you elements

– $('X').parent() – gets the immediate parent(s)

– $('X').children() – gets all child elements– $('X').next() – gets the next sibling

element(s)● You can always get to the actual DOM element

to get low-level aspects– $('X')[0].nextSibling – gets the next

node (could be a text node)

Page 24: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 24

© Copyright 2012, Software Alchemy

Up/Down Traversal

● Up traversal:– $('X').parent() – gets parent for each– $('X').parents() – gets all ancestors– $('X').parentsUntil('form') – gets a

subset of ancestors up to but not including the parent that matches the selector

● Down traversal:– $('X').children() – gets all direct children– $('X').find('.myClass') – finds all

descendants that match the selector

Page 25: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 25

© Copyright 2012, Software Alchemy

Sibling Traversal

● All siblings:– $('X').siblings() – gets all siblings– $('X').siblings('.myClass') – gets all

matching siblings● Next and Previous (not shown):

– $('X').next() – gets immediate next element– $('X').nextAll() – gets all next elements– $('X').nextUntil('.myClass') – get next

elements up to but not including the sibling matched by the selector

Page 26: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 26

© Copyright 2012, Software Alchemy

Selector Array Manipulation

● You can also manipulate the array returned by the $ function:

– Remove items: filter and not– Add items: add and andSelf– Selecting items: first, last, slice, eq

● Chaining:$('ol#section_list > li').eq(3).nextAll().andSelf().filter('.myClass');

$('ol#section_list').addClass('sectionListStyle') // one <ol> element .children('li').removeClass('highlighted') // list of <li> children .addClass('sectionItemStyle'); // same list of items

Page 27: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 27

© Copyright 2012, Software Alchemy

Wars& Warts

Low-levelframeworks High-level

frameworks

UsingPlugins

Manipulatingthe DOM

DEMO #1

JavaScriptFrameworks

Ajax

EventQueue

jQuery

Standard APIsjQuery Selectors

Std Traversal

jQuery Traversal

Queryingthe DOM

Traditional Model(s)

Std Model

jQuery EventRegistration

EventModel

Event Model

Page 28: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 28

© Copyright 2012, Software Alchemy

The Event Model(s)

● Traditional (AKA Level 0)– Event handlers as tag attributes (eg, onclick)– Event handlers set as Element properties

● Standard event model in DOM Level 2– Event listeners are registered with the element

● jQuery provides easy API and advanced (composite) events

Page 29: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 29

© Copyright 2012, Software Alchemy

Event Types

● Mouse:– click, dblclick, mousedown, mouseup,

mouseover, mousemove, mouseout● Keyboard:

– keypress, keydown, keyup● Window:

– load, unload, resize, scroll, abort, error● Form:

– focus, blur, select, change, reset, submit

Page 30: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 30

© Copyright 2012, Software Alchemy

Event Propagation

Element1

Element2

Event Bubbling

Netscape Model

Element1

Element2

Event Capturing

Microsoft Model

Page 31: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 31

© Copyright 2012, Software Alchemy

Traditional Event Handlers

● Assign handler on tag attribute<a href="#" onclick="return LoginScreen.validateForm();">go</a>

● Assign handler with Element propertyvar goButton = document.getElementById("goButton");goButton.onclick = function(event) { return Screen.validateForm(); };

● CONS:– Limited to only one handler per element and

event type– Poor separation of concerns: behavior mixed in

with structure– Inconsistent event propagation

Page 32: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 32

© Copyright 2012, Software Alchemy

DOM Level 2 Event Handlers

● HTML Elements are event targets:

«CORBA Interface»EventTarget

addEventListener(listener)removeEventListener(listener)dispatchEvent(event)

«CORBA Interface»EventListener

handleEvent(event)

0..*

«CORBA Interface»Event

type : DOMStringtarget : EventTarget {an element}currentTarget : EventTargeteventPhase : EventPhaseEnumtimeStamp : DOMTimeStamp

stopPropagation() : voidpreventDefault() : void

EventPhaseEnum

CAPTURING_PHASE = 1AT_TARGET = 2BUBBLING_PHASE = 3

Page 33: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 33

© Copyright 2012, Software Alchemy

Standard Event Propagation

● The standard propagation model is a combination of the proprietary models:

Element1

Element2

CAP

TUR

E_P

HAS

E

BUBB

LIN

G_P

HAS

EAT_TARGET

Page 34: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 34

© Copyright 2012, Software Alchemy

Event Registration (HTML)<body onload="EventsLevel2.registerHandlers(false);">

<h1>Event Model: Level 2 w/ No Capturing</h1>

<div id="outerBox"> Element1 <div id="innerBox"> Element2 </div></div>

</body>

Page 35: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 35

© Copyright 2012, Software Alchemy

Event Registration (JS)// Create the EventsLevel2 namespace var EventsLevel2 = {

registerHandlers: function(capture) { var outerBox = document.getElementById('outerBox'); var innerBox = document.getElementById('innerBox'); outerBox.addEventListener("click", EventsLevel2, capture); innerBox.addEventListener("click", EventsLevel2, capture); },

handleEvent : function(event) { var div = event.currentTarget; console.info("Current target: " + div.id + " had event: " + event + " in phase: " + event.eventPhase);

var propagate = confirm("Click OK to propagate the event."); if ( ! propagate ) event.stopPropagation(); }

} // END of EventsLevel2 namespace definition

Page 36: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 36

© Copyright 2012, Software Alchemy

jQuery Event Registration

● Methods on the jQuery object named after the specific DOM event

$('a#collapse_all_sections').click(function(event) { $('ol#section_list li ol').slideUp('slow'); event.preventDefault();});

● Implicit iteration allows easy handler registration across range of elements

$('ol#section_list > li').dblclick(function(event) { var $objectivesList = $(this).find('ol'); if ($objectivesList.is(':visible')) { $objectivesList.fadeOut(2000); } else { $objectivesList.fadeIn(2000); }});

Page 37: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 37

© Copyright 2012, Software Alchemy

jQuery Events

● Native Browser events:– Mouse,– Click,– Keyboard, ...

● Compound events:– hover is a combination of mouseover and

mouseout

– toggle is a sequence of click handlers● at least two● more than two switches in order, around robin

Page 38: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 38

© Copyright 2012, Software Alchemy

jQuery Examples (sketch)

● When hovering over a Section heading:$('div.section_head').hover(function(event) { // find the section_text DIV element // and position it near the mouse // and fade it in},function(event) { // and fade it out});

● When you click on the Control Panel to hide it:$('#control_panel h3').toggle(function(event) { // slide the panel contents away // and move the panel to the top of the screen},function(event) { // move the panel back to position // and slide the contents back into place});

Page 39: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 39

© Copyright 2012, Software Alchemy

Wars& Warts

Low-levelframeworks High-level

frameworks

UsingPlugins

DEMO #1

JavaScriptFrameworks

Ajax

EventQueue

jQuery

Standard APIsjQuery Selectors

Std Traversal

jQuery Traversal

Queryingthe DOM

Traditional Model(s)

Std Model

jQuery EventRegistration

EventModel

Std APIs

SettingAttributes

Setting CSSCreating Elements

Effects

Manipulatingthe DOM

Manipulating the DOM

Page 40: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 40

© Copyright 2012, Software Alchemy

DOM Manipulation

Document

createElement(tagName) : ElementcreateTextNode(data) : TextcreateCDATASection(data) : CDATASection

Element

tagName : DOMString

hasAttribute(attrName) : booleangetAttribute(attrName) : DOMStringsetAttribute(attrName, attrValue)removeAttribute(attrName)

1

documentElement{AKA: the root node}

Node

insertBeforereplaceChildremoveChildappendChild

Page 41: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 41

© Copyright 2012, Software Alchemy

Manipulation Example● From the Ajax example: start with empty <dl><dl id="definitions"></dl>

● Ajax callback fills in the listvar defList = document.getElementById('definitions');each(definitions, function (def) { var dt = document.createElement('dt'); dt.innerHTML = def.name; defList.appendChild(dt); var dd = document.createElement('dd'); dd.innerHTML = def.definition; defList.appendChild(dd);});

● The new DOM content:<dl id="definitions"> <dt>Ajax</dt> <dd>Asynchronous JavaScript and XML</dd> <dt>JavaScript</dt><dd>The standard browser scripting language</dd> <dt>Grails</dt> <dd>The hippest server-side scripting language</dd></dl>

Page 42: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 42

© Copyright 2012, Software Alchemy

jQuery DOM Manipulation

● The standard DOM manipulation APIs are fairly primitive

● jQuery (like other frameworks) provides a richer, cross-browser API.

– Accessing element attributes– Accessing CSS attributes– Creating, placing and removing elements– Graphical effects: hide, fade, slide

Page 43: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 43

© Copyright 2012, Software Alchemy

Element Attributes

● Get attributes with the attr(name) method<h4><abbr title='Objective'>O.</abbr>1.3</h4>

$('abbr').attr('title') ==> 'Objective'

● Set attributes with attr(name, value) <h4><abbr title='Objective'>O.</abbr>1.3</h4>

$('abbr').attr('title', 'Exam Objective')

==> becomes<h4><abbr title='Exam Objective'>O.</abbr>1.3</h4>

Page 44: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 44

© Copyright 2012, Software Alchemy

Element Classes

● The HTML attribute class is special because it actually may hold a space-delimited list:

<h2 id='bryan_actions' class='action_list'>Bryan Basham</h2>

● Add a class:$('#bryan_actions').addClass('open');<h2 id='bryan_actions' class='action_list open'>Bryan Basham</h2>

● Remove a class:$('#bryan_actions').removeClass('open').addClass('closed');// OR: $('#bryan_actions').toggleClass('open closed');<h2 id='bryan_actions' class='action_list closed'>Bryan Basham</h2>

● Testing the existence of a class:$('#bryan_actions').hasClass('open') ==> false$('#bryan_actions').hasClass('action_list') ==> true

Page 45: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 45

© Copyright 2012, Software Alchemy

CSS Style Properties

● While it is best to assign CSS style by applying the class property, you can also adjust styles directly on the DOM elements.

● Get style property (on first element in match):$('X').css('background-color'); ==> (eg) '#FFFFFF' (maybe) 'transparent'// OR use camelcase: $('X').css('backgroundColor');

● Set style properties (on all elements in match):$('X').css('background-color', 'red');

● To set multiple values use a map (object):$('X').css({'background-color': 'red', 'font-style': 'italic'});

Page 46: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 46

© Copyright 2012, Software Alchemy

DOM Creation

● Inject HTML directly into an element:<div class="demo-container"> <div class="demo-box">Demonstration Box</div></div>

$('demo-container').html('<p>New HTML</p>');

==> becomes:<div class="demo-container"> <p>New HTML</p></div>

● Create detached HTML:var $newPara = $('<p><em>New</em> Paragraph</p>');

Page 47: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 47

© Copyright 2012, Software Alchemy

DOM Insertion

● Append new DOM elements within:<div class="demo-container"> <div class="demo-box">Demonstration Box</div></div>

$('demo-container').append('<p>After</p>');

<div class="demo-container"> <div class="demo-box">Demonstration Box</div> <p>After</p></div>

● Prepend:$('demo-container').prepend('<p>Before</p>');

<div class="demo-container"> <p>Before</p> <div class="demo-box">Demonstration Box</div> <p>After</p></div>

Page 48: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 48

© Copyright 2012, Software Alchemy

DOM Removal

● Removing a DOM element:var $sectionLI = $('#' + Screen.sectionName(sectionIdx));$sectionLI.remove();

● Detaching a DOM elementvar $sectionLI = $('#' + Screen.sectionName(sectionIdx));$sectionLI.detach();

– Detached elements can be reattached without loss of registered event handlers

$('X').append($sectionLI);

Page 49: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 49

© Copyright 2012, Software Alchemy

Dynamic GUI Effects

● RIAs use simple graphical UI effects to help focus the user on relevant widgets or activities.

● jQuery provides a few simple effects:– show/hide – shows (or hides) whole DOM

elements and all children– fadeIn/fadeOut – a show/hide feature with fading

animation; the element fades out of existence– slideDown/slideUp – another show/hide feature

with animation that slides the content up and out of sight

Page 50: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 50

© Copyright 2012, Software Alchemy

Demo Handlers with Effects

● Section head click handler:// The “collapse all” button$('a#collapse_all_sections').click(function(event) { // slide closed the objectives lists of each section $('ol#section_list li ol').slideUp('slow'); event.preventDefault();});

● Section head double-click handler:$('ol#section_list li').dblclick(function(event) { var $objectivesList = $(this).find('ol'); // if the objectives list is visible if ($objectivesList.is(':visible')) { // then fade it out (snapping it out at the end) $objectivesList.fadeOut(2000); } else { // otherwise fade the list back onto the screen $objectivesList.fadeIn(2000); }});

Page 51: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 51

© Copyright 2012, Software Alchemy

Hover Example

● When hovering over a Section heading:$('div.section_head').hover(function(event) { // find the section_text DIV element $(event.target).find('div.section_text') // and position it near the mouse .css('left', event.pageX + 'px') .css('top', (event.pageY - $(window).scrollTop()) + 'px') // and fade it in .fadeIn('slow');},// hover out handlerfunction(event) { // and fade it out $(event.target).find('div.section_text').fadeOut('slow');});

● This implementation has a usability problem we will resolve later.

Page 52: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 52

© Copyright 2012, Software Alchemy

Wars& Warts

Low-levelframeworks High-level

frameworks

UsingPlugins

DEMO #1

JavaScriptFrameworks

EventQueue

jQuery

Standard APIsjQuery Selectors

Std Traversal

jQuery Traversal

Queryingthe DOM

Traditional Model(s)

Std Model

jQuery EventRegistration

EventModel

Std APIs

SettingAttributes

Setting CSSCreating Elements

ReviewjQuerySupport

DEMO #2

Ajax

Effects

Manipulatingthe DOM

Ajax using jQuery

Page 53: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 53

© Copyright 2012, Software Alchemy

Demo #2: Multi-User Interactions

● The Exam editor page:– In-place text editing– Periodically: users actions change the page– These actions are displayed in a side panel

Page 54: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 54

© Copyright 2012, Software Alchemy

Ajax Review

● Ajax provides a means to send requests to the server without refreshing the page.

● Ajax request:– URL– REST verbs– callback

● Ajax response:– Four phases but COMPLETE is all you need– Access to response status and text

Server

● Page requests● Ajax requests

User

Ajax requestAjax response (XML)

Ajax requestAjax response (XML)

Ajax requestAjax response (JSON)

Page requestPage response

Page 55: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 55

© Copyright 2012, Software Alchemy

Issuing Commands using Ajax

● Part of what a page may do is issue commands to the server:

Server

CommandServlet

CertExam

Section

Objective

CertDev

addSection{sectionIndex:7}

modifySection('title','...'){success:true}

EditExam requestEditExam page

Page 56: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 56

© Copyright 2012, Software Alchemy

Ajax Code to Send a Command

● The “Add Section” button sends a command to the server to create a new Section object

// attach the “Add Section” button's click handler$actionLink.click(function() { var command = Screen.makeCommand('addSection', { 'examCode' : Screen.EXAM_CODE, }); $.ajax('/SurveyTool/CommandProcessor', { type: 'POST', data: { 'command': JSON.stringify(command) }, success: function(respJSON) { Screen.insertSectionDOM(respJSON.sectionIdx); }, failure: function(errMsg) { console.error("errMsg %o", errMsg); } });});

URL

HTTP Method

Request Parameters

Successful response

Page 57: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 57

© Copyright 2012, Software Alchemy

jQuery Ajax Support

● The ajax method is the core API.● Specialized methods:

– get – GET request (needs configuration)– load – GET requests for HTML chunks– getJSON – GET request for JSON response– post – POST request

Page 58: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 58

© Copyright 2012, Software Alchemy

Wars& Warts

Low-levelframeworks High-level

frameworks

UsingPlugins

DEMO #1

JavaScriptFrameworks

jQuery

Standard APIsjQuery Selectors

Std Traversal

jQuery Traversal

Queryingthe DOM

Traditional Model(s)

Std Model

jQuery EventRegistration

EventModel

Std APIs

SettingAttributes

Setting CSSCreating Elements

ReviewjQuerySupport

DEMO #2

Ajax

Event TypesPeriodicEvents

DeferredEvents

DEMO #3

EventQueue

Effects

Manipulatingthe DOM

Event Queue

Page 59: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 59

© Copyright 2012, Software Alchemy

Event Queue

● All events that have an handler get added to a queue that is sorted by the time of the event.

● Each script is executed sequentially in the order the events happened.

● If any given script takes a long time then it can delay the execution of other event handlers.

● SO... make your event handler scripts as efficient as possible.

Page 60: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 60

© Copyright 2012, Software Alchemy

Queue ExampleScreen.buttonMouseOver

Screen.buttonClick

Screen.populateDefinitions

1331413671600

button / MouseOver

1331413671604

1331413671995

button / Click

1331413672005

1331413672025

Ajax request / state=COMPLETE

1331413672032

4ms 30ms 7ms

391ms 20ms

Page 61: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 61

© Copyright 2012, Software Alchemy

Types of Events

● User events are the majority– Clicking on buttons and links– Entering text– Submitting forms

● Ajax callbacks are handled as events● Timed events

– Periodic events (do over and over)– Deferred events (do once after a delay)

● jQuery effects, such as fadeOut, slideDown

Page 62: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 62

© Copyright 2012, Software Alchemy

Periodic Events

● Periodic Events are placed as evenly as possible on the queue:

Clock.displayTime

1331596413012

periodic event

1331596413017

5ms 1000ms

Clock.displayTime

1331596414012

periodic event

1331596414016

4ms 1000ms

Clock.displayTime

1331596415022

periodic event

1331596415026

4ms 1000ms

Clock.displayTime

1331596416019

periodic event

1331596416023

4ms

Page 63: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 63

© Copyright 2012, Software Alchemy

Multi-User Event Polling

Server

CommandServlet

CertExam

Section

Objective

EditExamCommandHandler

Bryan

Rob

EditExamaddSectionaddSectiongetCurrentEventsgetCurrentEvents

addSectiongetCurrentEvents

EditExam

addSection

getCurrentEvents

addObjective

getCurrentEventsmodifySection

Page 64: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 64

© Copyright 2012, Software Alchemy

Multi-User Event Polling (code)

● The Screen initializer starts the periodic poller:// start the action pollersetInterval(Screen.multiUserEventPoller, Screen.POLL_EVENTS_INTERVAL);

● Each period an Ajax request is sent:multiUserEventPoller : function() { var command = Screen.makeCommand('getCurrentEvents', { 'examCode': Screen.EXAM_CODE, }); $.ajax('/SurveyTool/CommandProcessor', { type: 'POST', data: { 'command': JSON.stringify(command) }, success: Screen.eventPollerSuccessCallback, failure: Screen.genericFailureCallback })},eventPollerSuccessCallback: function(respJSON) { $.each(respJSON.events, Screen.processUserEvent);},

Page 65: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 65

© Copyright 2012, Software Alchemy

Multi-User Event Poller (code2)

● The event process changes the page:processUserEvent: function(idx, actionEvent) { // process the action in the main content var eventName = actionEvent.eventName; switch (eventName) { case 'joinSession': Screen.addUserRegion(actionEvent.username, actionEvent.data); break; case 'addSection': Screen.insertSectionDOM(actionEvent.sectionIdx); break; // many more cases }; // add the action to the user's action history list Screen.addUserAction(actionEvent);},

● User event logging sketch:addUserAction: function(actionEvent) { // Create action name cell // Create action details cell // Add a row to that user's event display grid},

Page 66: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 66

© Copyright 2012, Software Alchemy

Deferred Events

● Some times responses to user actions need to be delayed (deferred)

– Example: the Section description hover effects; responds to fast when mousing across sections

– Solution: provide a script to be run after a small, but noticeable delay (just a sketch)

$('div.section_head').hover(function(event) { Screen._deferredEvent = event; Screen._deferredTimerId = setTimeout(showSectionText, 500);}, function() { if (Screen._deferredTimerId != null) { clearTimeout(Screen._deferredTimerId); } else { // fade out the Section text pop-up $(this).find('div.section_text').fadeOut('slow'); }});

Page 67: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 67

© Copyright 2012, Software Alchemy

Hover Lasts past Delay

● This timing chart shows how the delay works:Start hover

showSectionText()

Section heading / Hover In

500ms

Deferred Event invoked

Page 68: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 68

© Copyright 2012, Software Alchemy

Start hover

showSectionText()

Section heading / Hover In

500ms

Deferred Event invoked

Cancel deferred timer

Section heading / Hover Out

Hover Out before the Delay

● This timing chart shows deferred cancelation:

Page 69: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 69

© Copyright 2012, Software Alchemy

Wars& Warts

Low-levelframeworks High-level

frameworks

DEMO #1

JavaScriptFrameworks

jQuery

Standard APIsjQuery Selectors

Std Traversal

jQuery Traversal

Queryingthe DOM

Traditional Model(s)

Std Model

jQuery EventRegistration

EventModel

Std APIs

SettingAttributes

Setting CSSCreating Elements

ReviewjQuerySupport

DEMO #2

Ajax

Event TypesPeriodicEvents

DeferredEvents

DEMO #3

EventQueue

Effects

Manipulatingthe DOM

In-placeEditor

JQ UI& TabPanel

Data Tables

UsingPlugins

Using jQuery Plugins

Page 70: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 70

© Copyright 2012, Software Alchemy

jQuery Plugins

● jQuery (like many JS frameworks) supports custom plugins

● jQuery UI library (site, API)● Large community building plugins:

– Functional augmentation● Selectors● Utilities (eg, cookie management)

– GUI widgets● Grids, Editors, Layouts, Sliders, and so on...

Page 71: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 71

© Copyright 2012, Software Alchemy

In-place Editor

● DEMO: Section title and text editors

assignSectionEditor: function($attrHTML, attribute, sectionIdx) { $attrHTML.data('currentText', $attrHTML.text()); // attach jEditable to this GUI widget $attrHTML.editable(function(value, setting) { var currentText = $attrHTML.data('currentText'); if (value != currentText) { $attrHTML.data('currentText', value); Screen.sendSectionChange($attrHTML, attribute, value, sectionIdx); $attrHTML.addClass('pending'); return "Sending to server..."; } return value; }, // options to the plugin (next slide) Screen.makeEditableOptions(attribute));},

Click title to enablein-place editor.

Page 72: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 72

© Copyright 2012, Software Alchemy

jEditable Options

● Plugin Options patternmakeEditableOptions: function(attribute) { var options = { onblur: 'ignore', tooltip: 'Click to edit...', placeholder: "ENTER THE " + attribute.toUpperCase() }; if (attribute == 'title') { // textfield objects options.type = 'text'; options.width = 500; } else { // textarea objects options.type = 'textarea'; options.cols = 75; options.rows = 8; options.submit = 'OK'; options.cancel = 'Cancel'; } return options;},

Page 73: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 73

© Copyright 2012, Software Alchemy

jQuery UI Library

● GUI tools library from the jQuery team– Interactions:

● Draggable, Droppable, Resizeable...– Widgets:

● Tabs, Autocomplete, Datepicker, Button...– Effects

● More than just fade and slide: puff, bounce, drop...– Utilities

● Position: framework to position widgets relatively● Widget: custom widget framework

Page 74: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 74

© Copyright 2012, Software Alchemy

Example: Tab Panel

● DEMO: separate Exam grid by state

● Uses the following plugins:– jQuery UI– cookies– jqGrid

Page 75: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 75

© Copyright 2012, Software Alchemy

Tab Panel HTML

● HTML Structure of Tab Panel:<div id="certExamStateTabs"> <ul> <li><a href="#newExams"><span>New</span></a></li> <li><a href="#inDevelopmentExams"><span>In Development</span></a></li> <li><a href="#inEvaluationExams"><span>In Evaluation</span></a></li> <li><a href="#releasedExams"><span>Released</span></a></li> <li><a href="#retiredExams"><span>Retired</span></a></li> </ul><!-- Each DIV becomes on Tab panel for each Tab header defined above --> <div id='newExams'> <table id='newExamsGrid'></table> <div id='newExamsPager'></div> </div> <div id='inDevelopmentExams'> <table id='inDevelopmentExamsGrid'></table> <div id='inDevelopmentExamsPager'></div> </div> ...</div>

Page 76: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 76

© Copyright 2012, Software Alchemy

Tab Panel JavaScript

● JavaScript for the Tab Panel:$('#certExamStateTabs').tabs({// options object cookie: { expires: 30 }, // saves selected tab in cookie state show: function(event, ui) { Screen._showTab($(ui.panel)); }});

_showTab: function($tabPanel) { var tabPanelId = $tabPanel.attr('id'); // select and/or create the grid var $grid = Screen._attachGridToTab(tabPanelId); // resize the Grid after a delay (allowing the tab panel to be displayed) var thisScreen = this; setTimeout(function() { Screen._resizeGrid($tabPanel, $grid); },100);},

Page 77: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 77

© Copyright 2012, Software Alchemy

Exam Grids

● Server-side paging, sorted data grid:

<div id='newExams'> <table id='newExamsGrid'></table> <div id='newExamsPager'></div></div>

Page 78: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 78

© Copyright 2012, Software Alchemy

Grid JavaScript_createGrid: function(tabPanelId) { var stateCode = Screen.stateCodeByTabPanelId[tabPanelId]; var stateDesc = tabPanelId.split('Exams')[0]; return $('#' + tabPanelId + 'Grid').jqGrid({ url: 'QueryProcessor?queryName=examByState&state=' + stateCode, datatype: 'json', mtype: 'GET', colNames:['Id', 'Title', 'Category', 'State', 'Version'], colModel:[ {name:'id', index:'id', hidden:true} ,{name:'title', index:'title', width:100} ,{name:'category', index:'category', width:50} ,{name:'state', index:'state', width:50} ,{name:'version', index:'version', width:25} ], pager: '#' + tabPanelId + 'Pager', sortname: 'title', sortorder: 'asc', rowNum: 10, rowList: [10, 25, 50], viewrecords: true, emptyrecords: 'No ' + stateDesc + ' Exams found.', loadtext: 'Loading ' + stateDesc + ' Exams; please wait...', height: 300, width: 500 });}

Page 79: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 79

© Copyright 2012, Software Alchemy

Grid Ajax Request Structure

Server

QueryServlet

CertDev

GETQueryProcessor?queryName=examsByState&state=NEW&page=2&rows=10&sidx=title&sord=asc

{'page': 2, 'total': 4, // queryCount/pageSize 'records': 38, 'rows': [ {'id':42, 'cell': ['42', 'title', 'NEW', 'Java', ...]}, {'id':47, 'cell': ['47', ...]}, ... ]}

Dashboard request

Page 80: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 80

© Copyright 2012, Software Alchemy

Wars& Warts

Low-levelframeworks High-level

frameworks

DEMO #1

JavaScriptFrameworks

jQuery

Standard APIsjQuery Selectors

Std Traversal

jQuery Traversal

Queryingthe DOM

Traditional Model(s)

Std Model

jQuery EventRegistration

EventModel

Std APIs

SettingAttributes

Setting CSSCreating Elements

ReviewjQuerySupport

DEMO #2

Ajax

Event TypesPeriodicEvents

DeferredEvents

DEMO #3

EventQueue

Effects

Manipulatingthe DOM

In-placeEditor

JQ UI& TabPanel

Data Tables

UsingPlugins

Q & A

Page 81: Web Development using jQuery

RJUG: 10-April-2012

Bryan Basham – Web Development using jQuery Slide 81

© Copyright 2012, Software Alchemy

Resources

● Books:

– jQuery Reference Guide (PACKT)– Learning jQuery (PACKT)– DOM Scripting (friends of ed)– designing with web standards, 2nd ed. (New Riders)

● Web resources:

– jQuery: site and API – Douglas Crawford's site and lectures – JSON – Other Frameworks: Prototype, script.aculo.us, ExtJS, YUI, GWT,

Dojo, and so many more