Things You Might Not Know About jQuery




Creating Elements

$("<li/>");

Creating Elements

$("<li/>")
  .click(function(){})
  .attr("id", "test")
  .addClass("clickable");

Improved Creation

$("<li/>", {
  click: function(){},
  id: "test", // mix ids and jQuery methods
  addClass: "clickable"
});

Complex Creation

$("<li><a></a></li>") // li
  .find("a") // a
    .attr("href", "http://ejohn.org/") // a
    .html("John Resig") // a
  .end() // li
  .appendTo("ul");

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!

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;
});

Data Namespaces

$("div").data("events.plugin", { ... });

Event Namespaces

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

Custom Events

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

Custom Events

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

Special Events

Special Events

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 );
    }
  });
}

Submit and Change

Event Delegation

.delegate()

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

Live Events

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

.proxy()

var obj = { method: function(){} };
$("#foo").click( jQuery.proxy( obj, "method" ) );
$("#foo").unbind( "click", obj.method );

Custom Selectors

jQuery.expr[":"].myplugin = function(elem) {
  return !!jQuery.data("myplugin");
};

.load() page fragment

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

jQuery UI

Themeroller

jQuery CDN

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

Minified and Gzipped

Using Native APIs

What are we working on?

Bonus: (function(){})()

(function(window, undefined){
	// jQuery
})(this);

More Information