JavaScript Framework Translation Guide

05 Mar 2010

You may have already chosen your favorite JavaScript framework, but if you’re working on many different sites, chances are you need to know how to use some other frameworks as well. What follows is a mini translation dictionary: instructions for accomplishing some common tasks in jQuery, Prototype, MooTools, and YUI (versions 2 and 3). This should also serve as a means for superficial comparison of the libraries.

Event Listeners

DOM Ready

jQuery

$(document).ready(...);

Prototype

document.observe("dom:loaded", ...);

MooTools

window.addEvent("domready", ...);

YUI2

YAHOO.util.Event.onDOMReady(...);

YUI3

YUI().use("base", function(Y){
  Y.on("domready", ..., Y);
});

Page Fully Loaded (including images, etc)

jQuery

$(window).load(...);

Prototype

Event.observe(window, "load", ...);

MooTools

window.addEvent("load", ...);

YUI2

YAHOO.util.Event.onContentReady(...);

YUI3

YUI().use("base", function(Y){
  Y.on("load", ..., window);
});

Respond to Click Event

jQuery

$("#id").bind("click", function(event){...});

Prototype

$("id").observe("click", function(event){...});

MooTools

$("id").addEvent("click", function(event){...});

YUI2

YAHOO.util.Event.addListener("id", "click", function(event){...});

YUI3

YUI().use("node-base", function(Y){
  Y.on("click", function(event){...}, "#id");
});

DOM Manipulation

Note that most frameworks’ selectors return proxies (eg, a jQuery object) instead of actual DOM objects. Please see each framework’s documentation for methods of manipulating DOM elements.

Get Element By ID

jQuery

$("#id")

Prototype

$("id") // or $$("#id")

MooTools

$("id")

YUI2

YAHOO.util.Dom.get("id")

YUI3

YUI().use("node", function(Y){
  Y.one("#id");
});

Get All <p>s Within an Element

jQuery

$("#id p") // returns a jQuery object

Prototype

$$("#id p")

MooTools

$("id").getElements("p")

YUI2

YAHOO.util.Dom.getChildrenBy("id", function(el){
  return el.nodeName.toLowerCase() == "p";
})

YUI3

YUI().use("node", function(Y){
  Y.one("#id p");
});

Append Child Element to a Parent

jQuery

$("#id").append(...);

Prototype

$("id").insert(...);

MooTools

$("id").inject(...);

YUI2

YAHOO.util.Dom.get("id").appendChild(...);

YUI3

YUI().use("node", function(Y){
  Y.one("#id").appendChild(...);
});

AJAX

GET Request With Parameters (and Handle Successful Response)

jQuery

$.get("/url", {request: "params"}, function(data, status){...});

Prototype

new Ajax.Request("/url", {
  method:     "get",
  parameters: {request: "params"},
  onSuccess:  function(response){...}
});

MooTools

new Request({
  method:    "get",
  url:       "/url",
  data:      {request: "params"},
  onSuccess: function(text, xml){...}
});

YUI2

YAHOO.util.Connect.asyncRequest("GET", "/url?with=params", {
  success: function(response){...}
});

YUI3

YUI().use("io", function(Y){
  Y.io("/url?with=params", {
    on: {
      success: function(id, o, args){...}
    }
  });
});