Improve Your Web App with jQuery




Techniques

Improve Performance

Event Delegation

.delegate()

$("table").delegate("td", "hover", function(){
  $(this).toggleClass("active");
});

Live Events

$("a.menu").live("hover", function(){
  $(this).next().toggle(200);
  return false;
});

Caching with Fragments

$("<li><a></a></li>");

Document Fragments

var div = document.createElement("div");
div.innerHTML = "<li><a></a></li>";
var fragment = document.createDocumentFragment();
while ( div.firstChild ) {
  fragment.appendChild( div.firstChild );
}

Document Fragments

someDiv.appendChild( fragment ); // one operation!

jQuery from a CDN

<script src='http://code.jquery.com/jquery.js'></script>

Minified and Gzipped

Improve Accessibility

Unobtrusive Scripting

$("#somelink").click(function(){
  return false; // stop the browser from visiting the link
});

Ready Event

$(document).ready(function(){
	// Your jQuery code goes in here
});

Click and Load

$("a").click(function(){
  $(this).next().load( this.href );
  return false;
});

Extra Header

$_SERVER['HTTP_X_REQUESTED_WITH'];

.load() page fragment

$("div.load").load("file.html h2");
hello!

Reduce Complexity

Data Storage

$("div").data("test", 5);
$("div").data("test") === 5;

Internal Data Storage

// Get all event handlers bound to an element
$("div").data("events");

Removing Data

// Remove all data bound to an element
$("div").removeData();
$("div").remove(); // also removes data

Data Events

$("div").bind("getData.value", function(){
  return myPlugin.realValue;
});

Custom Events

$("div").bind("myplugin", someFn);
$("div").trigger("myplugin");

Event Namespaces

$("div").bind("click.plugin", someFn);
$("div").bind("focus.plugin", otherFn);
$("div").unbind(".plugin");

Events and Plugins

$("div").bind("remove.pluginA", someFn);
$("div").bind("remove.pluginB", otherFn);
$("div").trigger("remove");

Special Events

Focusin/Focusout

if ( document.addEventListener ) {
  jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
    jQuery.event.special[ fix ] = {
      setup: function() {
        this.addEventListener( orig, handler, true );
      }, 
      teardown: function() { 
        this.removeEventListener( orig, handler, true );
      }
    };

    function handler( e ) { 
      e = jQuery.event.fix( e );
      e.type = fix;
      return jQuery.event.handle.call( this, e );
    }
  });
}

Hotkeys

$(document).bind("keydown", "ctrl+a", function(){
  return false; // Prevent selecting all the text
});

Simplify Design

jQuery UI

Themeroller

What are we working on?

More Information