Se ha denunciado esta presentación.
Utilizamos tu perfil de LinkedIn y tus datos de actividad para personalizar los anuncios y mostrarte publicidad más relevante. Puedes cambiar tus preferencias de publicidad en cualquier momento.
Jazz up your JavaScript
Unobtrusive scripting with JavaScript libraries

              Simon Willison
         Webstock, 1...
This tutorial


• Unobtrusive scripting
• JavaScript libraries
• Writing unobtrusive scripts with jQuery
But first... let’s travel
back in time to 2004
(The only photo I could find of me in 2004)
JavaScript was the ugly duckling of the web standards world
Animated snowflakes
DHTML scripts copied and pasted from dynamicdrive.com
3 revolutions since 2004

•
    Ajax
• Unobtrusive scripting
• High quality open-source libraries
February 2005
The quieter revolutions
were just as important
Unobtrusive Scripting
Progressive enhancement
Rather than hoping for graceful degradation, PE
builds documents for the least capable or
differen...
Applied to JavaScript

• Build a site that works without JavaScript
• Use JavaScript to enhance that site to
  provide a b...
http://www.neighbourhoodfixit.com/
• Start with Plain Old Semantic HTML
• Layer on some CSS (in an external
  stylesheet) to apply the site’s visual design

...
Surely everyone has
JavaScript these days?
• There are legitimate reasons to switch it off
 • Some companies strip JavaScript at the
    firewall

  • Some people run...
The NoScript extension
Unobtrusive examples
labels.js




• One of the earliest examples of this
  technique, created by Aaron Boodman (now
  of Greasemonkey and Goog...
How it works
         <label for=quot;searchquot;>Search</label>
         <input type=quot;textquot; id=quot;searchquot; n...
easytoggle.js
  • An unobtrusive technique for revealing
     panels when links are clicked

<ul>
  <li><a href=quot;#pane...
How it works
•   When the page has loaded...

    •   Find all links with class=quot;togglequot; that reference an
       ...
Django filter lists

• Large multi-select boxes aren't much fun
 • Painful to scroll through
 • Easy to lose track of what ...
Mapping Microformats

• The hCard microformat provides a standard
  set of CSS classes for marking up an address
• Wouldn’...
•   When the page loads...

    •   Scan through for hCards (by looking for
        class=quot;vCardquot;)

    •   Extrac...
How about Ajax?
• Ajax is frequently used to avoid page refreshes
• So...
 • Write an app that uses full page refreshes
 •...
A simple example
Bad

Have you read our
<a href=quot;javascript:window.open(
   'terms.html', 'popup',
   'height=500,width=400,toolbar=no'...
Also bad

Have you read our
<a href=quot;#quot; onclick=quot;window.open(
   'terms.html', 'popup',
   'height=500,width=4...
Better

Have you read our
<a href=quot;terms.htmlquot;
 onclick=quot;window.open(
   'terms.html', 'popup',
   'height=500...
Better still

Have you read our
<a href=quot;terms.htmlquot;
 onclick=quot;window.open(
   this.href, 'popup',
   'height=...
Best

Have you read our
<a href=quot;terms.htmlquot;
  class=quot;sidenotequot;
>terms and conditions</a>?
Characteristics of
   unobtrusive scripts
• No in-line event handlers
• All code is contained in external .js files
• The s...
Handling events

function makeLinkPopup(link) {
    if (link.addEventListener) { // W3C spec browsers
	

   link.addEventL...
Handling events (2)
function popupClicked(ev) {
    // Find the link that was clicked
    ev = ev || window.event;
    var...
Handling events (3)
function setupLinks() {
  var links = document.getElementsByTagName('a');
  for (var i = 0, link; link...
That’s way too much
  nasty boilerplate
Unobtrusive challenges
• Adding events from pure script (avoiding
  inline script handlers) works differently
  between IE...
The onload problem
• All of these examples use code that runs
  when the window quot;loadquot; event is fired
  • Wait unti...
onDOMReady
•   A number of attempts have been made to create
    an onDOMReady event that fires when the
    DOM has been c...
So we need libraries

• Writing this stuff by hand is madness
• Boilerplate code to deal with browser
  inconsistencies is...
JavaScript Libraries
Controversial statement

• A year ago, there was a sizable debate over
    whether libraries were worth using at all -
   ...
“The bad news:
JavaScript is broken.
    The good news:
 It can be fixed with
  more JavaScript!”
              Geek folk s...
JavaScript characteristics
• Highly dynamic language
 • Most things can be introspected
 • Most things can be modified at r...
Modifying built-in types

var s = quot;This is a stringquot;;
alert(s.dasherize()); // Throws an error

String.prototype.d...
Functional programming
function hello() {
  alert(quot;helloquot;);
}

var hello = function() {
  alert(quot;helloquot;);
...
Functional programming
function hello() {
  alert(quot;helloquot;);
}

var hello = function() {
  alert(quot;helloquot;);
...
Functional programming
function hello() {
  alert(quot;helloquot;);
}

var hello = function() {
  alert(quot;helloquot;);
...
Closures

function outer() {
  var s = quot;This is a stringquot;;
  function inner() {
    alert(s);
  }
  inner();
}
Closures

function outer() {
  var s = quot;This is a stringquot;;
  function inner() {
    alert(s);
  }
  return inner;
...
Closures
function outer(s) {
  function inner() {
    alert(s);
  }
  return inner;
}

var sayHello = outer(quot;Helloquot...
Common library
   features
DOM selection


• document.getElementById shortcut
• Get elements by class name
• Get elements by CSS selector
CSS manipulation


• Manipulate and toggle classes
• Set styles (including opacity)
• Introspect applied styles
Event handling
• Cross-browser “run this function when this
  event happens to this element”
• Cross-browser “on DOM ready...
Ajax

• Cross-browser XMLHttpRequest
• Easier API for GET, POST and URL and form
  manipulation
• Support for Ajax formats...
Effects and animation

• Fades, wipes and transitions
• Custom animation of any CSS property
• Automatic frame-rate manage...
Widgets
• Packaged widgets for things like...
 • Sliders
 • Calendar date pickers
 • Fake “windows”
 • Auto-completers
 • ...
Language tools

• Iteration over objects and arrays
• Utilities for managing prototypal inheritance
• Traditional class-ba...
Array manipulation
for (var i = 0; i < arr.length; i++) {
   var item = arr[i];
   // process item
}

forEach(arr, functio...
Other characteristics
• Do they modify built in types?
• Global namespace impact
• Library size and componentization
• Sup...
The big five
• The Yahoo! User Interface Library
• Prototype (and Script.aculo.us)
• The Dojo Toolkit
• mooTools
• jQuery
The Example

• A login form that shakes its head at you
• Standard POST login form, unobtrusively
  upgraded to use Ajax a...
Simple login JSON API
• Responds to the same POST as the regular
   form, but looks for X-Requested-With:
   XMLHttpReques...
The Yahoo! User Interface Library
controls (aka widgets)

autocomplete           calendar           container


  menu                slider            tree...
YAHOO.util.Event.onDOMReady(function() {
    var $E = YAHOO.util.Event;
    var $D = YAHOO.util.Dom;
    var $C = YAHOO.ut...
YAHOO.util.Event.onDOMReady(function() {
    var $E = YAHOO.util.Event;
    var $D = YAHOO.util.Dom;
    var $C = YAHOO.ut...
YAHOO.util.Event.onDOMReady(function() {
    var $E = YAHOO.util.Event;
    var $D = YAHOO.util.Dom;
    var $C = YAHOO.ut...
YAHOO.util.Event.onDOMReady(function() {
    var $E = YAHOO.util.Event;
    var $D = YAHOO.util.Dom;
    var $C = YAHOO.ut...
$E.on(form, 'submit', function(ev) {
    $E.preventDefault(ev);
    var url = form.action;
    $C.setForm(form);
    $C.as...
success: function(response) {
  var json = eval('(' +
    response.responseText + ')');
  if (json.ok) {
    window.locati...
function shake(el, onComplete) {
    var $D = YAHOO.util.Dom;
    $D.setStyle(el, 'position', 'relative');
    var anim = ...
function shake(el, onComplete) {
    var $D = YAHOO.util.Dom;
    $D.setStyle(el, 'position', 'relative');
    var anim = ...
• Nice animation library, but a better way of
  chaining animations would be useful

• Severe namespacing (YAHOO was picke...
Download
                                                            Get the latest version—1.5.1


                      ...
document.observe('dom:loaded', function() {
    $('username').focus();
    var form = $$('form')[0];
    form.observe('sub...
onSuccess: function(response) {
    var json = response.responseJSON;
    if (json.ok) {
        window.location = json.re...
• Adds many functions to the global
  namespace ($, $$ etc) and extensively
  modifies built in types

• Heavily inspired b...
The Dojo Toolkit
dojo.require('dojox.fx');
djConfig.usePlainJson = true;

dojo.addOnLoad(function() {
  dojo.byId('username').focus();
  do...
load: function(json) {
  if (json.ok) {
    window.location = json.redirect;
  } else {
    form.style.position = 'relativ...
dojo.connect(last, 'onEnd', function() {
  if (!dojo.query('p.error').length) {
    var p = document.createElement('p');
 ...
• core, dijit and dojox:
 • Small, powerful abstraction library
 • Widget creation tools plus many widgets
 • “The future ...
mooTools
window.addEvent('domready', function() {
    $('username').focus();
    $$('form').addEvent('submit', function(ev) {
     ...
var fx = form.effects({
    duration: 100,
    transition: Fx.Transitions.Quart.easeOut
});
fx.start({left: -10}).chain(fu...
•   Started as an effects library for Prototype, now its
    own thing but Prototype influences are clear

•   No intention...
jQuery
jQuery(function($) {
  $('#username').focus();
  $('form').submit(function() {
    var $this = $(this);
    var url = $thi...
jQuery.fn.shake = function(callback) {
    this.css({'position': 'relative'});
    return this.animate(
        {left: '-1...
• Powerful, concise API based around CSS
  selector querying and chaining

• Excellent namespace management -
  everything...
Unobtrusive scripting
   with jQuery
Why jQuery

• It has the best balance between simplicity,
  productivity and good manners
• It has excellent documentation...
Why jQuery instead of...?

•   Unlike Prototype and mooTools...

    •   ... it doesn’t populate your global namespace

• ...
Learning

jQuery
in 45 minutes
jQuery philosophy

• Focus on the interaction between JavaScript
  and HTML
• (Almost) every operation boils down to:
 • F...
Sidenotes with jQuery

jQuery(function($) {
  $('a.sidenote').click(function() {
    window.open($(this).attr('href'), 'po...
Only one function!
• Absolutely everything* starts with a call to
  the jQuery() function
• Since it’s called so often, th...
jQuery('#nav')

jQuery('div#intro h2')

jQuery('#nav li.current a')
$('#nav')

$('div#intro h2')

$('#nav li.current a')
CSS 2 and 3 selectors

a[rel]

a[rel=quot;friendquot;]

a[href^=quot;http://quot;]

ul#nav > li

li#current ~ li (li sibli...
Magic selectors
div:first, h3:last
:header
:hidden, :visible
:animated
:input, :text, :password, :radio, :submit...
div:co...
jQuery collections
 •   $('div.section') returns a jQuery collection


 •   You can treat it like an array
$('div.section'...
jQuery collections
 •    $('div.section') returns a jQuery collection


 •    You can call methods on it
$('div.section')....
jQuery collections
 •    $('div.section') returns a jQuery collection


 •    You can call methods on it
$('div.section')....
HTML futzing


$('span#msg').text('The thing was updated!');



$('div#intro').html('<em>Look, HTML</em>');
Attribute futzing

$('a.nav').attr('href', 'http://flickr.com/');

$('a.nav').attr({

  'href': 'http://flickr.com/',

  '...
CSS futzing

$('#intro').addClass('highlighted');

$('#intro').removeClass('highlighted');

$('#intro').toggleClass('highl...
Grabbing values
 • Some methods return results from the first
    matched element
var height = $('div#intro').height();

va...
Traversing the DOM
 • jQuery provides enhanced methods for
    traversing the DOM
$('div.section').parent()

$('div.sectio...
Handling events

$('a:first').click(function(ev) {

  $(this).css({backgroundColor: 'orange'});

  return false; // Or ev....
Handling events

$('a:first').click(function(ev) {

  $(this).css({backgroundColor: 'orange'});

  return false; // Or ev....
Going unobtrusive


$(document).ready(function() {

  alert('The DOM is ready!');

});
Going unobtrusive


$(function() {

  alert('The DOM is ready!');

});
Going unobtrusive


jQuery(function($) {

  alert('The DOM is ready!');

});
Chaining

 • Most jQuery methods return another
    jQuery object - usually one representing the
    same collection. This...
Advanced chaining
• Some methods return a different collection
• You can call .end() to revert to the previous
  collection
Advanced chaining

 • Some methods return a different collection
 • You can call .end() to revert to the previous
    coll...
Ajax
 •   jQuery has excellent support for Ajax
$('div#intro').load('/some/file.html');

 •   More advanced methods includ...
Animation

 • jQuery has built in effects:
$('h1').hide('slow');

$('h1').slideDown('fast');

$('h1').fadeOut(2000);

 • Y...
Or roll your own...

$(quot;#blockquot;).animate({

   width: quot;+=60pxquot;,

   opacity: 0.4,

   fontSize: quot;3emqu...
Plugins


• jQuery is extensible through plugins, which
  can add new methods to the jQuery object
Further reading
• http://jquery.com/
• http://docs.jquery.com/
• http://visualjquery.com/ - API reference
• http://simonwi...
CSS futzing $('#intro').addClass('highlighted'); $('#intro').removeClass('highlighted'); $('#intro').toggleClass('highligh...
CSS futzing $('#intro').addClass('highlighted'); $('#intro').removeClass('highlighted'); $('#intro').toggleClass('highligh...
CSS futzing $('#intro').addClass('highlighted'); $('#intro').removeClass('highlighted'); $('#intro').toggleClass('highligh...
CSS futzing $('#intro').addClass('highlighted'); $('#intro').removeClass('highlighted'); $('#intro').toggleClass('highligh...
CSS futzing $('#intro').addClass('highlighted'); $('#intro').removeClass('highlighted'); $('#intro').toggleClass('highligh...
CSS futzing $('#intro').addClass('highlighted'); $('#intro').removeClass('highlighted'); $('#intro').toggleClass('highligh...
CSS futzing $('#intro').addClass('highlighted'); $('#intro').removeClass('highlighted'); $('#intro').toggleClass('highligh...
CSS futzing $('#intro').addClass('highlighted'); $('#intro').removeClass('highlighted'); $('#intro').toggleClass('highligh...
CSS futzing $('#intro').addClass('highlighted'); $('#intro').removeClass('highlighted'); $('#intro').toggleClass('highligh...
CSS futzing $('#intro').addClass('highlighted'); $('#intro').removeClass('highlighted'); $('#intro').toggleClass('highligh...
CSS futzing $('#intro').addClass('highlighted'); $('#intro').removeClass('highlighted'); $('#intro').toggleClass('highligh...
CSS futzing $('#intro').addClass('highlighted'); $('#intro').removeClass('highlighted'); $('#intro').toggleClass('highligh...
CSS futzing $('#intro').addClass('highlighted'); $('#intro').removeClass('highlighted'); $('#intro').toggleClass('highligh...
Próxima SlideShare
Cargando en…5
×

CSS futzing $('#intro').addClass('highlighted'); $('#intro').removeClass('highlighted'); $('#intro').toggleClass('highlighted'); Jazz up your JavaScript: Unobtrusive scripting with JavaScript libraries

33.901 visualizaciones

Publicado el

CSS futzing

$('#intro').addClass('highlighted');

$('#intro').removeClass('highlighted');

$('#intro').toggleClass('highlighted');



$('p').css('font-size', '20px');

$('p').css({'font-size': '20px', color: 'red'});

Publicado en: Tecnología
  • The Scrambler Unlock Her Legs | 95% Off by Bobby Rio-Rob Judge? ♣♣♣ http://ishbv.com/unlockher/pdf
       Responder 
    ¿Estás seguro?    No
    Tu mensaje aparecerá aquí
  • Unlock Her Legs - How to Turn a Girl On In 10 Minutes or Less... ◆◆◆ http://ishbv.com/unlockher/pdf
       Responder 
    ¿Estás seguro?    No
    Tu mensaje aparecerá aquí
  • We called it "operation mind control" - as we discovered a simple mind game that makes a girl become obsessed with you. (Aand it works even if you're not her type or she's already dating someone else) Here's how we figured it out... ◆◆◆ http://ishbv.com/unlockher/pdf
       Responder 
    ¿Estás seguro?    No
    Tu mensaje aparecerá aquí
  • Unlock Her Legs - How to Turn a Girl On In 10 Minutes or Less... ▲▲▲ http://t.cn/AijLRbnO
       Responder 
    ¿Estás seguro?    No
    Tu mensaje aparecerá aquí
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (Unlimited) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... Download Full EPUB Ebook here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... ACCESS WEBSITE for All Ebooks ......................................................................................................................... Download Full PDF EBOOK here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... Download EPUB Ebook here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... Download doc Ebook here { https://tinyurl.com/yyxo9sk7 } ......................................................................................................................... ......................................................................................................................... ......................................................................................................................... .............. Browse by Genre Available eBooks ......................................................................................................................... Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult,
       Responder 
    ¿Estás seguro?    No
    Tu mensaje aparecerá aquí

×