
JavaScript Framework Translation Guide
March 04, 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
$(document).ready(...);
document.observe("dom:loaded", ...);
window.addEvent("domready", ...);
YAHOO.util.Event.onDOMReady(...);
YUI().use("base", function(Y){
Y.on("domready", ..., Y);
});
Page Fully Loaded (including images, etc)
$(window).load(...);
Event.observe(window, "load", ...);
window.addEvent("load", ...);
YAHOO.util.Event.onContentReady(...);
YUI().use("base", function(Y){
Y.on("load", ..., window);
});
Respond to Click Event
$("#id").bind("click", function(event){...});
$("id").observe("click", function(event){...});
$("id").addEvent("click", function(event){...});
YAHOO.util.Event.addListener("id", "click", function(event){...});
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
$("#id")
$("id") // or $$("#id")
$("id")
YAHOO.util.Dom.get("id")
YUI().use("node", function(Y){
Y.one("#id");
});
Get All <p>s Within an Element
$("#id p") // returns a jQuery object
$$("#id p")
$("id").getElements("p")
YAHOO.util.Dom.getChildrenBy("id", function(el){
return el.nodeName.toLowerCase() == "p";
})
YUI().use("node", function(Y){
Y.one("#id p");
});
Append Child Element to a Parent
$("#id").append(...);
$("id").insert(...);
$("id").inject(...);
YAHOO.util.Dom.get("id").appendChild(...);
YUI().use("node", function(Y){
Y.one("#id").appendChild(...);
});
AJAX
GET Request With Parameters (and Handle Successful Response)
$.get("/url", {request: "params"}, function(data, status){...});
new Ajax.Request("/url", {
method: "get",
parameters: {request: "params"},
onSuccess: function(response){...}
});
new Request({
method: "get",
url: "/url",
data: {request: "params"},
onSuccess: function(text, xml){...}
});
YAHOO.util.Connect.asyncRequest("GET", "/url?with=params", {
success: function(response){...}
});
YUI().use("io", function(Y){
Y.io("/url?with=params", {
on: {
success: function(id, o, args){...}
}
});
});
■