Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries
-
Upload
simon-willison -
Category
Technology
-
view
130 -
download
2
description
Transcript of Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries
![Page 1: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/1.jpg)
Jazz up your JavaScriptUnobtrusive scripting with JavaScript libraries
Simon WillisonWebstock, 11th February 2008
![Page 2: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/2.jpg)
• Unobtrusive scripting
• JavaScript libraries
• Writing unobtrusive scripts with jQuery
This tutorial
![Page 3: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/3.jpg)
But first... let’s travel back in time to 2004
![Page 4: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/4.jpg)
(The only photo I could find of me in 2004)
![Page 5: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/5.jpg)
JavaScript was the ugly duckling of the web standards world
![Page 6: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/6.jpg)
Animated snowflakes
![Page 7: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/7.jpg)
DHTML scripts copied and pasted from dynamicdrive.com
![Page 8: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/8.jpg)
• Unobtrusive scripting
• High quality open-source libraries
3 revolutions since 2004
• Ajax
![Page 9: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/9.jpg)
February 2005
![Page 10: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/10.jpg)
![Page 11: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/11.jpg)
![Page 12: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/12.jpg)
The quieter revolutions were just as important
![Page 13: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/13.jpg)
Unobtrusive Scripting
![Page 14: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/14.jpg)
Rather than hoping for graceful degradation, PE builds documents for the least capable or differently capable devices first, then moves on to enhance those documents with separate logic for presentation, in ways that don't place an undue burden on baseline devices but which allow a richer experience for those users with modern graphical browser software.
Progressive enhancement
Steven Champeon and Nick Finck, 2003
![Page 15: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/15.jpg)
Applied to JavaScript
• Build a site that works without JavaScript
• Use JavaScript to enhance that site to provide a better user experience: easier to interact with, faster, more fun
![Page 16: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/16.jpg)
http://www.neighbourhoodfixit.com/
![Page 17: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/17.jpg)
![Page 18: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/18.jpg)
![Page 19: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/19.jpg)
• Start with Plain Old Semantic HTML
• Layer on some CSS (in an external stylesheet) to apply the site’s visual design
• Layer on some JavaScript (in an external script file) to apply the site’s enhanced behaviour
![Page 20: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/20.jpg)
Surely everyone has JavaScript these days?
![Page 21: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/21.jpg)
• There are legitimate reasons to switch it off
• Some companies strip JavaScript at the firewall
• Some people run the NoScript Firefox extension to protect themselves from common XSS and CSRF vulnerabilities
• Many mobile devices ignore JS entirely
• Screen readers DO execute JavaScript, but accessibility issues mean that you may not want them to
![Page 22: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/22.jpg)
The NoScript extension
![Page 23: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/23.jpg)
Unobtrusive examples
![Page 24: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/24.jpg)
• One of the earliest examples of this technique, created by Aaron Boodman (now of Greasemonkey and Google Gears fame)
labels.js
![Page 25: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/25.jpg)
![Page 26: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/26.jpg)
![Page 27: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/27.jpg)
• Once the page has loaded, the JavaScript:
• Finds any label elements linked to a text field
• Moves their text in to the associated text field
• Removes them from the DOM
• Sets up the event handlers to remove the descriptive text when the field is focused
• Clean, simple, reusable
<label for="search">Search</label><input type="text" id="search" name="q">
How it works
![Page 28: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/28.jpg)
• An unobtrusive technique for revealing panels when links are clicked
<ul> <li><a href="#panel1" class="toggle">Panel 1</a></li> <li><a href="#panel2" class="toggle">Panel 2</a></li> <li><a href="#panel3" class="toggle">Panel 3</a></li></ul>
<div id="panel1">...</div><div id="panel2">...</div><div id="panel3">...</div>
easytoggle.js
![Page 29: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/29.jpg)
![Page 30: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/30.jpg)
![Page 31: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/31.jpg)
• When the page has loaded...
• Find all links with class="toggle" that reference an internal anchor
• Collect the elements that are referenced by those anchors
• Hide all but the first
• Set up event handlers to reveal different panels when a link is clicked
• Without JavaScript, links still jump to the right point
How it works
![Page 32: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/32.jpg)
• Large multi-select boxes aren't much fun
• Painful to scroll through
• Easy to lose track of what you have selected
• Django's admin interface uses unobtrusive JavaScript to improve the usability here
Django filter lists
![Page 33: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/33.jpg)
![Page 34: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/34.jpg)
![Page 35: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/35.jpg)
Mapping Microformats
• The hCard microformat provides a standard set of CSS classes for marking up an address
• Wouldn’t it be great if we could unobtrusively plot them on a Google Map...
![Page 36: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/36.jpg)
![Page 37: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/37.jpg)
![Page 38: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/38.jpg)
• When the page loads...
• Scan through for hCards (by looking for class="vCard")
• Extract the street address and postcode for each one
• Pass it to the Google Maps geocoder to get the lat/long point
• Insert a div for the Google Map, instantiate it and add the points as markers
![Page 39: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/39.jpg)
• Ajax is frequently used to avoid page refreshes
• So...
• Write an app that uses full page refreshes
• Use unobtrusive JS to "hijack" links and form buttons and use Ajax instead
• Jeremy Keith coined the term "Hijax" to describe this
How about Ajax?
![Page 40: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/40.jpg)
A simple example
![Page 41: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/41.jpg)
![Page 42: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/42.jpg)
Have you read our <a href="javascript:window.open( 'terms.html', 'popup', 'height=500,width=400,toolbar=no' );">terms and conditions</a>?
Bad
![Page 43: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/43.jpg)
Have you read our <a href="#" onclick="window.open( 'terms.html', 'popup', 'height=500,width=400,toolbar=no' ); return false;" >terms and conditions</a>?
Also bad
![Page 44: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/44.jpg)
Have you read our <a href="terms.html" onclick="window.open( 'terms.html', 'popup', 'height=500,width=400,toolbar=no' ); return false;" >terms and conditions</a>?
Better
![Page 45: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/45.jpg)
Have you read our <a href="terms.html" onclick="window.open( this.href, 'popup', 'height=500,width=400,toolbar=no' ); return false;" >terms and conditions</a>?
Better still
![Page 46: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/46.jpg)
Have you read our <a href="terms.html" class="sidenote" >terms and conditions</a>?
Best
![Page 47: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/47.jpg)
Characteristics of unobtrusive scripts
• No in-line event handlers
• All code is contained in external .js files
• The site remains usable without JavaScript
• Existing links and forms are repurposed
• JavaScript dependent elements are dynamically added to the page
![Page 48: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/48.jpg)
function makeLinkPopup(link) { if (link.addEventListener) { // W3C spec browsers link.addEventListener('click', popupClicked, false); } else if (link.attachEvent) { // Internet Explorer link.attachEvent('onclick', popupClicked); } else { return; // Fail silently in ancient browsers }}
Handling events
![Page 49: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/49.jpg)
function popupClicked(ev) { // Find the link that was clicked ev = ev || window.event; var link = ev.target || ev.srcElement; if (link.nodeType == 3) { // Safari bug fix link = link.parentNode; } window.open(link.href, 'popup', 'height=500,width=400,toolbar=no'); // Now prevent the default link action if (ev.preventDefault) { ev.preventDefault(); // W3C spec browsers } else { ev.returnValue = false; // Internet Explorer }}
Handling events (2)
![Page 50: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/50.jpg)
function setupLinks() { var links = document.getElementsByTagName('a'); for (var i = 0, link; link = links[i]; i++) { if (link.className == 'sidenote') { makeLinkPopup(link); } }}
if (window.addEventListener) { window.addEventListener('load', setupLinks, false);} else if (window.attachEvent) { window.attachEvent('onload', setupLinks);}
Handling events (3)
![Page 51: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/51.jpg)
That’s way too much nasty boilerplate
![Page 52: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/52.jpg)
Unobtrusive challenges
• Adding events from pure script (avoiding inline script handlers) works differently between IE and other browsers
• Cancelling default actions (link navigation, form submission) also works differently
• Scripts that add behaviour need to execute as soon as the DOM is available
![Page 53: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/53.jpg)
• All of these examples use code that runs when the window "load" event is fired
• Wait until page is loaded, then manipulate the DOM
• Problem: If the page takes a while to load (large inline images) there will be a Flash Of Unstyled Content (FOUC)
• Also, if the user clicks things before the setup code has fired they won't get the expected behaviour.
The onload problem
![Page 54: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/54.jpg)
• A number of attempts have been made to create an onDOMReady event that fires when the DOM has been constructed but before the page has loaded
• dean.edwards.name/weblog/2006/06/again/
• Modern libraries all support this in some form
• One caveat: CSS may not have loaded, so calculated dimensions may be incorrect
onDOMReady
![Page 55: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/55.jpg)
So we need libraries
• Writing this stuff by hand is madness
• Boilerplate code to deal with browser inconsistencies is the number one enemy of unobtrusive scripting
• Thankfully, today these are all solved problems
![Page 56: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/56.jpg)
JavaScript Libraries
![Page 57: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/57.jpg)
Controversial statement
• A year ago, there was a sizable debate over whether libraries were worth using at all - many people preferred to just “roll their own”
• Today, that argument is over. Libraries have won.
• (some may disagree)
![Page 58: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/58.jpg)
“The bad news: JavaScript is broken.
The good news:It can be fixed with more JavaScript!”
Geek folk saying
![Page 59: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/59.jpg)
JavaScript characteristics• Highly dynamic language
• Most things can be introspected
• Most things can be modified at runtime
• Functional programming, anonymous functions and closures
• Ability to modify behaviour of built-in types
• Prototypal inheritance - arguably more powerful than class-based inheritance, though much less widely understood
![Page 60: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/60.jpg)
Modifying built-in types
var s = "This is a string";alert(s.dasherize()); // Throws an error
String.prototype.dasherize = function() { return this.toLowerCase().replace(/\s+/g, '-');}
alert(s.dasherize()); // this-is-a-string
![Page 61: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/61.jpg)
Functional programming
function hello() { alert("hello");}
var hello = function() { alert("hello");}
(function() { alert("hello");})();
![Page 62: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/62.jpg)
Functional programming
function hello() { alert("hello");}
var hello = function() { alert("hello");}
(function() { alert("hello");})();
![Page 63: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/63.jpg)
Functional programming
function hello() { alert("hello");}
var hello = function() { alert("hello");}
(function() { alert("hello");})();
![Page 64: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/64.jpg)
Closures
function outer() { var s = "This is a string"; function inner() { alert(s); } inner();}
![Page 65: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/65.jpg)
Closures
function outer() { var s = "This is a string"; function inner() { alert(s); } return inner;}
var func = outer();func(); // Alerts "This is a string";
![Page 66: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/66.jpg)
Closures
function outer(s) { function inner() { alert(s); } return inner;}
var sayHello = outer("Hello");var sayGoodbye = outer("Goodbye");sayHello();sayGoodbye();
![Page 67: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/67.jpg)
Common library features
![Page 68: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/68.jpg)
DOM selection
• document.getElementById shortcut
• Get elements by class name
• Get elements by CSS selector
![Page 69: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/69.jpg)
CSS manipulation
• Manipulate and toggle classes
• Set styles (including opacity)
• Introspect applied styles
![Page 70: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/70.jpg)
Event handling
• Cross-browser “run this function when this event happens to this element”
• Cross-browser “on DOM ready” support
• Cross-browser event introspection: where was the event targetted?
• Event triggering
• Custom events
![Page 71: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/71.jpg)
Ajax
• Cross-browser XMLHttpRequest
• Easier API for GET, POST and URL and form manipulation
• Support for Ajax formats: HTML fragments, JSON, XML
![Page 72: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/72.jpg)
Effects and animation
• Fades, wipes and transitions
• Custom animation of any CSS property
• Automatic frame-rate management
• Easing
![Page 73: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/73.jpg)
Widgets• Packaged widgets for things like...
• Sliders
• Calendar date pickers
• Fake “windows”
• Auto-completers
• Grids and treeviews
• Support for drag-and-drop
![Page 74: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/74.jpg)
Language tools
• Iteration over objects and arrays
• Utilities for managing prototypal inheritance
• Traditional class-based inheritance
• Tools for managing scope and callbacks
• Dynamic code loading
![Page 75: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/75.jpg)
Array manipulation
for (var i = 0; i < arr.length; i++) { var item = arr[i]; // process item}
forEach(arr, function(item) { // process item});
doubles = map(arr, function(i) { return i * 2 });evens = filter(arr, function(i) { return i % 2 == 0 });
![Page 76: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/76.jpg)
Other characteristics• Do they modify built in types?
• Global namespace impact
• Library size and componentization
• Support for accessibility (esp. for widgets)
• Browser support
• Documentation
• Community
![Page 77: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/77.jpg)
The big five
• The Yahoo! User Interface Library
• Prototype (and Script.aculo.us)
• The Dojo Toolkit
• mooTools
• jQuery
![Page 78: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/78.jpg)
The Example
• A login form that shakes its head at you
• Standard POST login form, unobtrusively upgraded to use Ajax and shake if the password is incorrect
• Behind the scenes, JSON is used for the reply to say if the password was correct or not
![Page 79: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/79.jpg)
Simple login JSON API
• Responds to the same POST as the regular form, but looks for X-Requested-With: XMLHttpRequest header
• If login fails, returns
{"ok":false}
• If login succeeds, returns
{"ok": true, "redirect": "loggedin.php"}
![Page 80: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/80.jpg)
The Yahoo! User Interface Library
![Page 81: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/81.jpg)
dom event connection
animation dragdrop
utilities
controls (aka widgets)
autocomplete calendar
menu slider treeview
container
![Page 82: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/82.jpg)
YAHOO.util.Event.onDOMReady(function() { var $E = YAHOO.util.Event; var $D = YAHOO.util.Dom; var $C = YAHOO.util.Connect; var query = YAHOO.util.Selector.query; $D.get('username').focus(); var form = query('form')[0];
![Page 83: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/83.jpg)
YAHOO.util.Event.onDOMReady(function() { var $E = YAHOO.util.Event; var $D = YAHOO.util.Dom; var $C = YAHOO.util.Connect; var query = YAHOO.util.Selector.query; $D.get('username').focus(); var form = query('form')[0];
![Page 84: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/84.jpg)
YAHOO.util.Event.onDOMReady(function() { var $E = YAHOO.util.Event; var $D = YAHOO.util.Dom; var $C = YAHOO.util.Connect; var query = YAHOO.util.Selector.query; $D.get('username').focus(); var form = query('form')[0];
![Page 85: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/85.jpg)
YAHOO.util.Event.onDOMReady(function() { var $E = YAHOO.util.Event; var $D = YAHOO.util.Dom; var $C = YAHOO.util.Connect; var query = YAHOO.util.Selector.query; $D.get('username').focus(); var form = query('form')[0];
![Page 86: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/86.jpg)
$E.on(form, 'submit', function(ev) { $E.preventDefault(ev); var url = form.action; $C.setForm(form); $C.asyncRequest( 'POST', url, { success: function() { ... } } );});
![Page 87: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/87.jpg)
success: function(response) { var json = eval('(' + response.responseText + ')'); if (json.ok) { window.location = json.redirect; } else { $D.get('password').value = ''; $D.get('password').focus(); shake(form, function() { if (!query('p.error').length) { var p = document.createElement('p'); p.className = 'error'; p.innerHTML = 'Incorrect password.'; form.insertBefore(p, form.firstChild); } }); }
![Page 88: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/88.jpg)
function shake(el, onComplete) { var $D = YAHOO.util.Dom; $D.setStyle(el, 'position', 'relative'); var anim = new YAHOO.util.Anim(el, { left: {to: -10} }, 0.1, YAHOO.util.Easing.easeOut); anim.onComplete.subscribe(function() { // ... } anim.animate();}
![Page 89: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/89.jpg)
function shake(el, onComplete) { var $D = YAHOO.util.Dom; $D.setStyle(el, 'position', 'relative'); var anim = new YAHOO.util.Anim(el, { left: {to: -10} }, 0.1, YAHOO.util.Easing.easeOut); anim.onComplete.subscribe(function() { var anim2 = new YAHOO.util.Anim(el, { left: {to: 10} }, 0.1, YAHOO.util.Easing.easeOut); anim2.onComplete.subscribe(function() { var anim3 = new YAHOO.util.Anim(el, { left: {to: -10} }, 0.1, YAHOO.util.Easing.easeOut); anim3.onComplete.subscribe(function() { var anim4 = new YAHOO.util.Anim(el, { left: {to: 10} }, 0.1, YAHOO.util.Easing.easeOut); anim4.onComplete.subscribe(function() { var anim5 = new YAHOO.util.Anim(el, { left: {to: 0} }, 0.1, YAHOO.util.Easing.easeOut); if (onComplete) { anim5.onComplete.subscribe(onComplete); } anim5.animate(); }); anim4.animate(); }); anim3.animate(); }); anim2.animate(); }); anim.animate();}
![Page 90: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/90.jpg)
• Nice animation library, but a better way of chaining animations would be useful
• Severe namespacing (YAHOO was picked because it was so ugly no one would ever have used it for an existing variable)
• Not too many shortcuts outside of dealing with browser difficulties
• Excellent documentation
![Page 91: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/91.jpg)
Download API Docs Tips and Tutorials Blog Discuss Contribute
Prototype is a JavaScript Framework that aims toease development of dynamic web applications.
Featuring a unique, easy-to-use toolkit for class-driven
development and the nicest Ajax library around, Prototype
is quickly becoming the codebase of choice for web
application developers everywhere.
Prototype and script.aculo.us: The "Bungee
book" has landed!
Core team member Christophe
Porteneuve has been hard at work
for the past few months tracking
and documenting Prototype for his
new book Prototype and
script.aculo.us, which is now
available as a Beta Book from the
Pragmatic Programmers (and is
scheduled to ship later this year).
Read more !
DownloadGet the latest version—1.5.1
LearnOnline documentation and resources.
DiscussMailing list and IRC
ContributeSubmit patches and report bugs.
Who's using Prototype?
Meet the developers
© 2006-2007 Prototype Core Team | Licenses: MIT (source code) and CC BY-SA (documentation).
Prototype and Script.aculo.us
![Page 92: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/92.jpg)
document.observe('dom:loaded', function() { $('username').focus(); var form = $$('form')[0]; form.observe('submit', function(ev) { ev.preventDefault(); var url = form.action; new Ajax.Request(url, { parameters: form.serialize(), onSuccess: ... }); });});
![Page 93: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/93.jpg)
onSuccess: function(response) { var json = response.responseJSON; if (json.ok) { window.location = json.redirect; } else { form.shake(); // No apparent way of setting an // "on finished" callback setTimeout(function() { if (!$$('p.error').length) { var p = new Element( 'p', {'class': 'error'} ).insert('Incorrect...'); form.insertBefore(p, form.firstChild); } }, 500); $('password').value = ''; $('password').focus(); }}
![Page 94: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/94.jpg)
• Adds many functions to the global namespace ($, $$ etc) and extensively modifies built in types
• Heavily inspired by Ruby and Ruby on Rails
• Useful shortcuts and nice effects
• Documentation still leaves something to be desired - API docs for Prototype, incomplete wiki docs for Scriptaculous
![Page 95: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/95.jpg)
The Dojo Toolkit
![Page 96: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/96.jpg)
dojo.require('dojox.fx');djConfig.usePlainJson = true;
dojo.addOnLoad(function() { dojo.byId('username').focus(); dojo.query('form').connect('submit', function(ev) { dojo.stopEvent(ev); var form = this; var url = form.action; dojo.xhrPost({ handleAs: 'json', headers: {'X-Requested-With': 'XMLHttpRequest'}, url: url, form: form, load: function(json) { ... } }); });});
![Page 97: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/97.jpg)
load: function(json) { if (json.ok) { window.location = json.redirect; } else { form.style.position = 'relative'; var last = dojo.animateProperty({ node: form, duration: 100, properties: {left: {end: 0}} }); var leftArgs = { node: form, duration: 100, properties: {left: {end: -10}} }; var rightArgs = { node: form, duration: 100, properties: {left: {end: 10}} }; dojo.fx.chain([ dojo.animateProperty(leftArgs), dojo.animateProperty(rightArgs), dojo.animateProperty(leftArgs), dojo.animateProperty(rightArgs), last ]).play();
![Page 98: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/98.jpg)
dojo.connect(last, 'onEnd', function() { if (!dojo.query('p.error').length) { var p = document.createElement('p'); p.className = 'error'; p.innerHTML = 'Incorrect username or password.'; form.insertBefore(p, form.firstChild); } }); dojo.byId('password').value = ''; dojo.byId('password').focus();
![Page 99: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/99.jpg)
• core, dijit and dojox:
• Small, powerful abstraction library
• Widget creation tools plus many widgets
• “The future today” genius extensions
• Documentation has improved with the Dojo Book, but still patchy in places
![Page 100: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/100.jpg)
mooTools
![Page 101: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/101.jpg)
window.addEvent('domready', function() { $('username').focus(); $$('form').addEvent('submit', function(ev) { new Event(ev).stop(); var form = this; var url = form.action; form.send({ onComplete: function(data) { var json = Json.evaluate(data); if (json.ok) { window.location = json.redirect; } else { form.style.position = 'relative'; // ... animation here $('password').value = ''; $('password').focus(); } } }); });});
![Page 102: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/102.jpg)
var fx = form.effects({ duration: 100, transition: Fx.Transitions.Quart.easeOut});fx.start({left: -10}).chain(function(){ this.start({left: 10});}).chain(function(){ this.start({left: -10});}).chain(function(){ this.start({left: 10});}).chain(function(){ this.start({left: 0});}).chain(function() { if (!$$('p.error').length) { var p = new Element('p'). addClass('error').setHTML( 'Incorrect username or password.' ); form.insertBefore(p, form.firstChild); }});
![Page 103: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/103.jpg)
• Started as an effects library for Prototype, now its own thing but Prototype influences are clear
• No intention at all of playing nicely with other libraries
• Good API documentation (including a mootorial) but not much else, and major changes between library versions
• I found the API unintuitive compared to the others
![Page 104: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/104.jpg)
jQuery
![Page 105: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/105.jpg)
jQuery(function($) { $('#username').focus(); $('form').submit(function() { var $this = $(this); var url = $this.attr('action'); var data = $this.serialize(); jQuery.post(url, data, function(json) { if (json.ok) { window.location = json.redirect; } else { $('#password').val('').focus(); $this.shake(function() { if (!$this.find('p.error').length) { $this.prepend('<p class="error">Incorrect ...</p>'); } }); } }, 'json'); return false; });});
![Page 106: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/106.jpg)
jQuery.fn.shake = function(callback) { this.css({'position': 'relative'}); return this.animate( {left: '-10px'}, 100 ).animate( {left: '+10px'}, 100 ).animate( {left: '-10px'}, 100 ).animate( {left: '+10px'}, 100 ).animate( {left: '0px'}, 100, callback );};
![Page 107: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/107.jpg)
• Powerful, concise API based around CSS selector querying and chaining
• Excellent namespace management - everything lives on the one jQuery symbol which is aliased to $, with the option to revert
• Excellent support for plugins
• The best documentation out of all of the libraries
![Page 108: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/108.jpg)
Unobtrusive scripting with jQuery
![Page 109: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/109.jpg)
Why jQuery
• It has the best balance between simplicity, productivity and good manners
• It has excellent documentation
• You can learn the whole library in less than an hour
![Page 110: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/110.jpg)
Why jQuery instead of...?
• Unlike Prototype and mooTools...
• ... it doesn’t populate your global namespace
• Unlike YUI...
• ... it’s extremely succinct
• Unlike Dojo...
• ... you can learn it in 45 minutes!
![Page 111: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/111.jpg)
Learning
jQueryin 45 minutes
![Page 112: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/112.jpg)
jQuery philosophy
• Focus on the interaction between JavaScript and HTML
• (Almost) every operation boils down to:
• Find some stuff
• Do something to it
![Page 113: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/113.jpg)
Sidenotes with jQuery
jQuery(function($) { $('a.sidenote').click(function() { window.open($(this).attr('href'), 'popup', 'height=500,width=400,toolbar=no'); return false; });});
![Page 114: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/114.jpg)
Only one function!
• Absolutely everything* starts with a call to the jQuery() function
• Since it’s called so often, the $ variable is set up as an alias to jQuery
• If you’re also using another library you can revert to the previous $ function with jQuery.noConflict();
* not entirely true
![Page 115: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/115.jpg)
jQuery('#nav')
jQuery('div#intro h2')
jQuery('#nav li.current a')
![Page 116: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/116.jpg)
$('#nav')
$('div#intro h2')
$('#nav li.current a')
![Page 117: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/117.jpg)
CSS 2 and 3 selectors
a[rel]
a[rel="friend"]
a[href^="http://"]
ul#nav > li
li#current ~ li (li siblings that follow #current)
li:first-child, li:last-child, li:nth-child(3)
![Page 118: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/118.jpg)
Magic selectors
div:first, h3:last
:header
:hidden, :visible
:animated
:input, :text, :password, :radio, :submit...
div:contains(Hello)
![Page 119: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/119.jpg)
jQuery collections
• $('div.section') returns a jQuery collection
• You can treat it like an array
$('div.section').length = no. of matched elements
$('div.section')[0] - the first div DOM element
$('div.section')[1]
$('div.section')[2]
![Page 120: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/120.jpg)
jQuery collections
• $('div.section') returns a jQuery collection
• You can call methods on it
$('div.section').size() = no. of matched elements
$('div.section').each(function() {
console.log(this);
});
![Page 121: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/121.jpg)
jQuery collections
• $('div.section') returns a jQuery collection
• You can call methods on it
$('div.section').size() = no. of matched elements
$('div.section').each(function(i) {
console.log("Item " + i + " is ", this);
});
![Page 122: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/122.jpg)
HTML futzing
$('span#msg').text('The thing was updated!');
$('div#intro').html('<em>Look, HTML</em>');
![Page 123: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/123.jpg)
Attribute futzing
$('a.nav').attr('href', 'http://flickr.com/');
$('a.nav').attr({
'href': 'http://flickr.com/',
'id': 'flickr'
});
$('#intro').removeAttr('id');
![Page 124: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/124.jpg)
CSS futzing
$('#intro').addClass('highlighted');
$('#intro').removeClass('highlighted');
$('#intro').toggleClass('highlighted');
$('p').css('font-size', '20px');
$('p').css({'font-size': '20px', color: 'red'});
![Page 125: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/125.jpg)
Grabbing values
• Some methods return results from the first matched element
var height = $('div#intro').height();
var src = $('img.photo').attr('src');
var lastP = $('p:last').html()
var hasFoo = $('p').hasClass('foo');
var email = $('input#email').val();
![Page 126: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/126.jpg)
Traversing the DOM
• jQuery provides enhanced methods for traversing the DOM
$('div.section').parent()
$('div.section').next()
$('div.section').prev()
$('div.section').nextAll('div')
$('h1:first').parents()
![Page 127: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/127.jpg)
Handling events
$('a:first').click(function(ev) {
$(this).css({backgroundColor: 'orange'});
return false; // Or ev.preventDefault();
});
![Page 128: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/128.jpg)
Handling events
$('a:first').click(function(ev) {
$(this).css({backgroundColor: 'orange'});
return false; // Or ev.preventDefault();
});
$('a:first').click();
![Page 129: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/129.jpg)
Going unobtrusive
$(document).ready(function() {
alert('The DOM is ready!');
});
![Page 130: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/130.jpg)
Going unobtrusive
$(function() {
alert('The DOM is ready!');
});
![Page 131: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/131.jpg)
Going unobtrusive
jQuery(function($) {
alert('The DOM is ready!');
});
![Page 132: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/132.jpg)
Chaining
• Most jQuery methods return another jQuery object - usually one representing the same collection. This means you can chain methods together:
$('div.section').hide().addClass('gone');
![Page 133: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/133.jpg)
Advanced chaining
• Some methods return a different collection
• You can call .end() to revert to the previous collection
![Page 134: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/134.jpg)
Advanced chaining
• Some methods return a different collection
• You can call .end() to revert to the previous collection
$('#intro').css('color', '#cccccc').
find('a').addClass('highlighted').end().
find('em').css('color', 'red').end()
![Page 135: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/135.jpg)
Ajax
• jQuery has excellent support for Ajax
$('div#intro').load('/some/file.html');
• More advanced methods include:
$.get(url, params, callback)
$.post(url, params, callback)
$.getJSON(url, params, callback)
$.getScript(url, callback)
![Page 136: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/136.jpg)
Animation
• jQuery has built in effects:$('h1').hide('slow');
$('h1').slideDown('fast');
$('h1').fadeOut(2000);
• You can chain them:$('h1').fadeOut(1000).slideDown()
![Page 137: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/137.jpg)
$("#block").animate({
width: "+=60px",
opacity: 0.4,
fontSize: "3em",
borderWidth: "10px"
}, 1500);
Or roll your own...
![Page 138: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/138.jpg)
Plugins
• jQuery is extensible through plugins, which can add new methods to the jQuery object
![Page 139: Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries](https://reader034.fdocuments.us/reader034/viewer/2022051110/54c79b2f4a79594a1f8b4569/html5/thumbnails/139.jpg)
Further reading
• http://jquery.com/
• http://docs.jquery.com/
• http://visualjquery.com/ - API reference
• http://simonwillison.net/tags/jquery/
• http://simonwillison.net/2007/Aug/15/jquery/
• http://24ways.org/2007/unobtrusively-mapping-microformats-with-jquery