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.
$(document).ready(...);
document.observe("dom:loaded", ...);
window.addEvent("domready", ...);
YAHOO.util.Event.onDOMReady(...);
YUI().use("base", function(Y){
Y.on("domready", ..., Y);
});
$(window).load(...);
Event.observe(window, "load", ...);
window.addEvent("load", ...);
YAHOO.util.Event.onContentReady(...);
YUI().use("base", function(Y){
Y.on("load", ..., window);
});
$("#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");
});
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.
$("#id")
$("id") // or $$("#id")
$("id")
YAHOO.util.Dom.get("id")
YUI().use("node", function(Y){
Y.one("#id");
});
$("#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");
});
$("#id").append(...);
$("id").insert(...);
$("id").inject(...);
YAHOO.util.Dom.get("id").appendChild(...);
YUI().use("node", function(Y){
Y.one("#id").appendChild(...);
});
$.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){...}
}
});
});