o ts l re o m ^ it b a

I'm Remy.
Who uses jQuery.

I'm Remy. Who uses jQuery? .

• Who & Why • Get going • What's new • Oldies but goodies • Dev patterns .

WARNING! A LOT OF CODE AHEAD. .

Who's using jQuery? .

.

com capitalone.com ibm.com w3.com dell.gov microsoft.org .com twitpic.com bing.Who's using jQuery? reddit.com whitehouse.com espn.ly tv.com amazon.builtwith.com boxee.com wordpress.com time.com http://trends.com twitter.com netflix.com overstock.com stackoverflow.tv bit.com/javascript/jquery monster.

11 platforms Accessible to both coder and designer .Why use jQuery • • • • • • Simplifies and speeds up web development Avoid cross-browser headaches Large pool of plugins Large and active community Tested on 50 browsers.

Why use jQuery • • • • • • Simplifies and speeds up web development Avoid cross-browser headaches Large pool of plugins Large and active community Tested on 50 browsers. 11 platforms Accessible to both coder and designer .

Installation .

Hosting options • Host it yourself (good for offline dev) • Hotlink it: • Media Temple • Microsoft • Google (my pick) http://docs.jquery.com/Downloading_jQuery .

CDN FTW .

<html> <head> <styles> <!-.make me beautiful --> </styles> </head> <body> <content> <!-.ooo.make me learned --> </content> <behaviour> <!-. matron --> </behaviour> </body> </html> .

matron --> </behaviour> </body> </html> .make me beautiful --> </styles> </head> <body> <content> <!-.Styles first let's the page render without scripts blocking <html> <head> <styles> <!-.ooo.make me learned --> </content> <behaviour> <!-.

Finally.make me beautiful --> </styles> </head> <body> <content> <!-. the jQuery and sexy magic jazz. matron --> </behaviour> </body> </html> . <html> <head> <styles> <!-.make me learned --> </content> <behaviour> <!-.ooo. add your behaviour.

The quick start guide .

length.getElementsByTagName('tr').test(rows[i].DOM Scripting var tables = document. } } } .getElementsByTagName('table'). t < tables. i += 2) { if (!/(^|s)odd(s|$)/.length. for (var t = 0. i < rows. t++) { ! ! var rows = tables[t].className += ' odd'. for (var i = 1.className)) { rows[i].

addClass('odd'). .jQuery simplifies $('table tr:nth-child(odd)').

jQuery simplifies jQuery function $('table tr:nth-child(odd)'). .addClass('odd').

CSS expression .jQuery simplifies jQuery function $('table tr:nth-child(odd)').addClass('odd').

addClass('odd'). CSS expression .jQuery simplifies jQuery function jQuery method $('table tr:nth-child(odd)').

.addClass('odd').jQuery simplifies $('table tr:nth-child(odd)').

API features 1. Effects: slide. filter . events. fade. get. post. roll your own 4. Ajax: JSON. roll your own 3. Events: click. find. mouseover. hover. show/hide. load. keydown 2. parent. DOM navigation: children.

find. post. events. get. roll your own 3.API features 1. keydown 2. parent. fade. Effects: slide. show/hide. roll your own 4. Events: click. filter . DOM navigation: children. load. mouseover. hover. Ajax: JSON.

Events: click. load. events. show/hide. roll your own 3.API features 1. mouseover. post. roll your own 4. Effects: slide. get. Ajax: JSON. fade. find. filter . hover. keydown 2. parent. DOM navigation: children.

Events: click. roll your own 3. mouseover. keydown 2. find. events. Effects: slide. load. get. DOM navigation: children. post. parent. fade. hover. show/hide.API features 1. filter . roll your own 4. Ajax: JSON.

Effects: slide. hover. mouseover. filter 1. Ajax: JSON.lotnavigation: more! 2. roll your own . Events: click. fade.API features and a whole4. load. keydown 3. roll your own children. parent. events. DOM get. find. post. show/hide.

$(this). }).fadeIn(). return false. .fadeOut().$('div').click(function () { alert('you clicked me').

fadeOut().click(function () { alert('you clicked me').$('div'). $(this). . }).fadeIn(). return false.

fadeIn().$('div').click(function () { alert('you clicked me'). }). $(this). return false. .fadeOut().

.$('div'). return false. }). $(this).click(function () { alert('you clicked me').fadeOut().fadeIn().

fadeOut(). $(this). .fadeIn(). }).click(function () { alert('you clicked me').$('div'). return false.

.click(function () { alert('you clicked me').fadeIn(). return false. $(this). }).$('div').fadeOut().

}).click(function () { alert('you clicked me'). .$('div').fadeIn(). return false. $(this).fadeOut().

$('div'). }).fadeOut().fadeIn(). . return false. $(this).click(function () { alert('you clicked me').

$('div').fadeOut().click(function () { alert('you clicked me').fadeIn(). . }). $(this). return false.

return false. }).click(function () { alert('you clicked me').fadeIn(). $(this).fadeOut(). .$('div').

$(this).fadeOut().click(function () { alert('you clicked me'). }).fadeIn(). .$('div'). return false.

return false. $(this). }).click(function () { alert('you clicked me'). .fadeOut().$('div').fadeIn().

}).click(function () { alert('you clicked me').fadeOut(). .$('div').fadeIn(). return false. $(this).

2 The sexy bits.4. .1.

Attributes in $ .

print().$('<a id="printlink">Print this page</a>'). .click(function () { window. return false. }).

'printlink') .$('<a/>') .click(function () { window. .print(). }).text('Print this page') . return false.attr('id'.

text: 'Print this page'. return false. { id: 'printlink'. } }).print(). click: function () { window. .$('<a/>'.

Bulk binding .

.keydown(updateDisplay) .focus(updateDisplay) .$('a') .blur(somethingElse).

. blur: somethingElse }).bind({ focus: updateDisplay.$('a'). keydown: updateDisplay.

blur: somethingElse }).bind({ 'keydown focus': updateDisplay.$('a'). .

callback for setters .

• css • attr • val • text • html • addClass • toggleClass • removeClass • after • before • append • prepend • wrap • wrapAll • wrapInner • replaceWith .

$('div').replace(/foo/. }). 'bar') ). .html().html( $(this).each(function () { $(this).

each(function () { $(this).replace(/foo/. 'bar'). }).html(function (i. $('div').html().$('div').replace(/foo/. html) { return html. }). .html( $(this). 'bar') ).

attr('value'. attr) { return attr + i.$('input'). function (i. }). <input <input <input <input type="text" type="text" type="text" type="text" value="remy" /> value="bruce" /> value="andy" /> value="ribot" /> .

<input <input <input <input type="text" type="text" type="text" type="text" value="remy0" /> value="bruce1" /> value="andy2" /> value="ribot3" /> . }). attr) { return attr + i. function (i.$('input').attr('value'.

text().addClass(function () { return 'who-' + $(this). }).$('li').find('a'). <li><a href="#remy">Remy</a></li> <li><a href="#bruce">Bruce</a></li> <li><a href="#andy">Andy</a></li> <li><a href="#ribot">Ribot</a></li> .

text(). }).$('li').find('a'). <li class="who-Remy"><a href="#remy">Remy</a></li> <li class="who-Bruce"><a href="#bruce">Bruce</a></li> <li class="who-Andy"><a href="#andy">Andy</a></li> <li class="who-Ribot"><a href="#ribot">Ribot</a></li> .addClass(function () { return 'who-' + $(this).

') + ')'.replace(/[^\d. css) { css = css.').join('. ''). function (i) { return 255 .$('*').css('backgroundColor'. }). function (i. . return 'rgb(' + $.map(css.]/g.split('.i. }).

.

.

css) { css = css. }).split('.'). return 'rgb(' + $.]/g.$('*'). function (i.i. }). .') + ')'.replace(/[^\d. function (i) { return 255 .css('backgroundColor'.map(css.join('. '').

parseJSON .jQuery.

live .Segue: .

Problem .

</script> .jpg"> <img src="spotty.jpg"> <img src="txspete.js"> <script> $('img'). the jQuery runs <h1>Super Ted</h1> <img src="superted. }).When the page has finished loading.click(function(){ showDetails(this).jpg"> <script src="jquery.

Clicking these images "shows details"

<h1>Super Ted</h1> <img src="superted.jpg"> <img src="spotty.jpg"> <img src="txspete.jpg"> <script src="jquery.js"> <script> $('img').click(function(){ showDetails(this); }); </script>

Now Ajax (or something else) add new images to the page

<h1>Super Ted</h1> <img src="superted.jpg"> <img src="spotty.jpg"> <img src="txspete.jpg"> <script src="jquery.js"> <script> $('img').click(function(){ showDetails(this); }); </script>

Now Ajax (or something else) add new images to the page

<h1>Super Ted</h1> <img src="superted.jpg"> <img src="spotty.jpg"> <img src="txspete.jpg"> <img src="mothernature.jpg"> <script src="jquery.js"> <script> $('img').click(function(){ showDetails(this); }); </script>

jpg"> <img src="spotty.js"> <script> $('img'). </script> .jpg"> <img src="mothernature.jpg"> <script src="jquery. <h1>Super Ted</h1> <img src="superted.jpg"> <img src="txspete.Clicking this image doesn't do anything. }).click(function(){ showDetails(this).

Solution: event delegation

$('p').live('click', fn);
<p>Ninja</p> <p>Dizzy</p> <script src="jquery.js"></script> <script> $('p').live('click', function () { $(this).after('<p>' + $(this).text() + ' clicked</p>'); }); </script>

$('p').live('click', fn);
<p>Ninja</p> <p>Dizzy</p> <script src="jquery.js"></script> <script> $('p').live('click', function () { $(this).after('<p>' + $(this).text() + ' clicked</p>'); }); </script>

live('click'. fn).text() + ' clicked</p>').live('click'. function () { $(this).after('<p>' + $(this). }).$('p').js"></script> <script> $('p'). </script> . <p>Ninja</p> <p>Dizzy</p> <script src="jquery.

fn). function () { $(this). </script> .$('p').live('click'. }). <p>Ninja</p> <p>Dizzy</p> <script src="jquery.js"></script> <script> $('p').text() + ' clicked</p>').live('click'.after('<p>' + $(this).

live('click'.live('click'. fn).js"></script> <script> $('p').after('<p>' + $(this). </script> . <p>Ninja</p> <p>Dizzy</p> <script src="jquery.$('p'). function () { $(this).text() + ' clicked</p>'). }).

.

live('click'.$('p').fn) .

jQuery registers 'click' for live events .fn) 1.live('click'.$('p').

$('p'). When click fires on the top level element. run the selector ('p') .fn) 1.live('click'. jQuery registers 'click' for live events 2.

target). When click fires on the top level element. If the $(event.is(selector) then run handler . jQuery registers 'click' for live events 2.live('click'. run the selector ('p') 3.$('p').fn) 1.

live events .

Now Full Coverage • submit • change • focus (via "focusin") • blur (via "focusout") .

.focusout " This is distinct from the blur event in that it supports detecting the loss of focus from parent elements (in other words. it supports events bubbling).

delegate .

fn). event.delegate(selector.$('root'). .

delegate('a'.$('div'). fn). 'click'. .

'click'. . fn).delegate('a'.div handles the event delegation $('div').

fn). 'click'. watching for when 'a' elements are - .$('div').delegate('a'.

. . fn). $('div').clicked.delegate('a'. 'click'.

delegate('a'.$('div'). running the event handler when that happens . fn). 'click'.

live is slow(er) ..

doStuff). .$('div').live('click'.

live('click'.wasteful selection of 'div's $('div'). . doStuff).

Better done using delegate $('div'). .live('click'. doStuff).

'click'.delegate( 'div'.$(document). . doStuff ).

Hat tip: Cory Hart . $.root.delegate( 'div'. 'click'.$. doStuff ).root = $(document).

proxy .$.

.var user = { name: "rem". } }. test: function () { alert(this.name).

} }.test().name). . test: function () { alert(this. user.var user = { name: "rem".

user. } }. test: function () { alert(this.var user = { name: "rem".name).test(). .

. test: function () { alert(this.var user = { name: "rem". $('a').click(user.name). } }.test). // user.test().

// user. } }.name).click(user. test: function () { alert(this.var user = { Fail name: "rem". $('a'). :( .test().test).

// user. $('a'). } }. test: function () { alert(this. :( .test().var user = { Fail name: "rem".name).test).click(user.

$('a'). } }.test.proxy(user.name).click( $. user) ). test: function () { alert(this.var user = { name: "rem". .

var user = { name: "rem". } }.name).click( $.test. user) ). test: function () { alert(this. . $('a').proxy(user.

.click( $. user) ). } }.name). test: function () { alert(this.test.proxy(user. $('a').var user = { name: "rem".

What about that this? .

} }. $('a').test. test: function () { alert(this.proxy(user.var user = { name: "rem". user) ). .name).click( $.

currentTarget).click( $. user) ).proxy(user. } }. $('a'). alert(this.test. test: function (event) { alert(event. .var user = { name: "rem".name).

Per property easing .

uk/sandbox/jquery/easing/ .animate({ top: 500. http://gsgd. 'easeOutBounce').co. }.$('#ball'). left: 200. 2000.

2000).$('#ball').animate({ top: [500. left: 500 }. . 'easingOutBounce'].

$('#ball'). 2000).animate({ top: [500. . left: 500 }. 'easingOutBounce'].

delay .

animate({ top: 50. }. . 200) . 200) . }.animate({ left: 50.animate({ left: 400. 200) . }.$('#ball') .animate({ top: 400. 200). }.

delay(1000) .animate({ left: 50.delay(1000) .animate({ top: 250. 200) . }. }.$('#ball') . 200) . }.animate({ left: 250.delay(1000) . 200) .

What's not new .

$('div').length .

$('remy').length .

doStuff = function () { return this. .each(function () { // do. }.stuff })..$.fn..

stuff }) : this..fn. .each(function () { // do.doStuff = function () { return this..length ? this.$. }.

. . }.$.each(function () { // do.length ? this.doStuff = function () { return this.fn..stuff }) : this.

$...length ? this. .stuff }) : this. }.fn.each(function () { // do.doStuff = function () { return this.

off = true .$.fx.

Ajax events .Loading...

Ajax events
1. ajaxStart 2. ajaxSuccess (or ajaxError) 3. ajaxComplete

$('#status').ajaxStart(function () { $(this).fadeIn(); }).ajaxComplete(function () { $(this).fadeOut(); });

$.extend .

options).s = $. size:'L' colour:'blue' size:'M' . defaults.extend({}.

size:'L' colour:'blue' size:'M' .extend({}. options). defaults.s = $.

extend({}. options). size:'M' colour:'blue' size:'L' colour:'blue' size:'M' . defaults.s = $.

's' is the result of {} extended s = $. size:'M' colour:'blue' size:'L' colour:'blue' size:'M' . options).extend({}. defaults.

extend(defaults. size:'L' colour:'blue' size:'M' .s = $. options).

options).s = $.extend(defaults. size:'M' colour:'blue' size:'M' .

s = $.extend(defaults. options). s === defaults size:'M' colour:'blue' size:'M' .

var linkTemplate = { mouseover: function () { // default mouse over stuff }. . focus: function () { // default focus } click: function () { // do default click stuff } }.

.$('<a/>'. $.linkTemplate.extend({}.{ click: function () { // do custom click } })).

extend({}.$('<a/>'.linkTemplate. $.{ click: function () { // do custom click } })). .

linkTemplate.$('<a/>'.{ click: function () { // do custom click } })).extend({}. . $.

{ click: function () { // do custom click } })).extend({}.linkTemplate. $.$('<a/>'. .

{ click: function () { // do custom click } })). $. .extend({}.$('<a/>'.linkTemplate.

7 deadly sins .

live or .1 .delegate? .

delegate • Wasteful selection • Doesn't chain • Doesn't work with DOM elements • No wasteful selection • Less distance for event to bubble • Chains .live vs.

delegate .Use .

2 $('div').get(0) .

.// Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this. }.slice(num)[ 0 ] : this[ num ] ).

toArray() : // Return just the object ( num < 0 ? this.slice(num)[ 0 ] : this[ num ] ). . }.// Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.

$('div')[0] .

click(fn) .3 $('div').

fn ) : this.attrFn ) { jQuery.split(" ").each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error").fn[ name ] = function( fn ) { return fn ? this.bind( name.trigger( name ). name ) { // Handle event binding jQuery. . }.attrFn[ name ] = true. if ( jQuery. } }).jQuery. function( i.

bind( name.attrFn[ name ] = true. fn ) : this.split(" "). } }). name ) { // Handle event binding jQuery. function( i. .attrFn ) { jQuery.trigger( name ). if ( jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error"). }.jQuery.fn[ name ] = function( fn ) { return fn ? this.

$('div').bind('click',fn)

4
$(this).data('key')

$(this).data({ key1: 'foo', key2: 'bar' });

// 'foo' .key1. obj.data().var obj = $(this).

length ) { return jQuery.each(function() { jQuery. }). } . key ).data( this[0] ).data: function( key. value ) { if ( typeof key === "undefined" && this.data( this. } else if ( typeof key === "object" ) { return this.

key ). } else if ( typeof key === "object" ) { return this.data: function( key.each(function() { jQuery. } .length ) { return jQuery. }).data( this[0] ).data( this. value ) { if ( typeof key === "undefined" && this.

$. 'key') .data(this.

obj.var obj = $.key1. // "foo" .data(this).

5 CSS belongs in style sheets. .

css({ position: 'absolute'. . left: '50%'.foo'). top: 0.$('. background: '#c00' }).

background: #c00. top: 0.. left: 50%.foo { position: absolute. } .

.$('div').addClass('foo').

6 $('div'. '#foo') .

} .find(expr) } else { return jQuery( context ). context) // (which is just equivalent to: $(context).// HANDLE: $(expr.find( selector ).

$('#foo').find('div') .

7 Avoid the DOM .

. reduce when you touch it.The DOM is slow.

}). .append(tweet). function (tweet) { $('#tweets').each(tweets.$.

}).push(tweet).append(html. function (tweet) { html.var html = []. $.each(tweets. . $('#tweets').join('')).

function (tweet) { html.each(tweets. $('#tweets').append(html. .push(tweet). }).join('')). $.var html = [].

slides: http://j.com .mp/jquery-rs You've now been jQuerified! Any questions? @rem remy@leftlogic.

Sign up to vote on this title
UsefulNot useful