Moving from Prototype to JQuery

Posted by Brian in tips, web (November 15th, 2009)

On a recent project, I converted a ton of Javascript from Prototype to jQuery in order to take advantage of many of the nice UI elements available. As I did the conversion, I took down some notes that I wanted to share with you about the differences between the two libraries. In some cases, the differences are insignificant, and in a couple of others, the differences merely come down to a difference of opinion among the developers and supporters of the libraries.

Here are the notes:

Getting Ready

Before you can work with elements on the page, those elements must be loaded.

Prototype uses

document.observe("dom:loaded", function() {
  // your functions
})

jQuery uses this:

$(document).ready(function(){
  // your functions
})

Finding things

In Prototype, you use $() or $$() to locate elements. With $() you use the ID, whereas with $$() you use a CSS selector.

  var header = $("header");  // a single element, <div id="header"
  var popups = $$("a.popup"); // all elements like <a class="popup">

With JQuery, you do almost all of your element location using $(), which works very much like $$() in Prototype.

  var header = $("#header");  // a single element, <div id="header"
  var popups = $("a.popup"); // all elements like <a class="popup">

Binding events

Prototype’s Element class has an Observe method. It’s very easy to use and easy on the eyes.

  $("header").observe("click", function(event){
    alert("Hi there");
  });

In jQuery, it’s nearly identical, except that click is a method on the JQuery object.

  $("#header").click(function(event){
    alert("Hi there");
  });

At first, the differences look marginal, but let’s look at a more complicated example:

In Prototype, to find all links on the page with the class “Popup” and make them open in a new window, you have to do this:

function new_window_links(){
  links = $$("a.popup");
  links.each(function(link){
    link.observe("click", function(event){
      window.open(link.href);
      event.stop();
    });
  });
}

The Prototype version makes us find all of the elements, loop over them, and then apply the observer to each one.

jQuery can hide the iteration from you, which results in somewhat cleaner code.

function new_window_links(){
  links = $("a.popup").click(function(event){
      window.open($(this).attr('href'));
      event.preventDefault();
  });
}

Adding Classes

Prototype:

   $(".foo").addClassName("ninja");
  $(".foo").addClass("ninja");

Traversing the DOM

Prototype:

  parent_of_foo = $("foo").up();

jQuery

  parent_of_foo = $("#foo").parent();

Working with HTML attributes

This one was the most difficult to get used to. In Prototype, many of the HTML attributes are available as methods on the Element class.

  window.open(link.href);

In jQuery, you use the attr method to get and set the attributes.

  window.open(link.attr("http");

This illustrates only a few of the differences between the libraries, but as you can see, the differences don’t realy amount to anything substantial. Both of these libraries greatly simplify cross-browser JavaScript development, so no matter which you choose, you’ll be in good shape.

3 Responses to ' Moving from Prototype to JQuery '

Subscribe to comments with RSS or TrackBack to ' Moving from Prototype to JQuery '.

  1. DL said,
    on December 23rd, 2009 at 6:44 am

    I don’t know if this treatment is related to your disability, but thought it might be worth a look if/when it’s released:

    http://www.engadget.com/2009/12/23/stem-cell-therapy-restores-british-mans-eyesight/

  2. on October 7th, 2010 at 6:35 am

    I never quite understood the draw of JQuery until I watched a video of John Resig talking about JQuery. It became quite clear very quickly that JQuery is an opinionated framework. As a person who uses Rails, I’m sure you understand opinionated frameworks. In a talk by Scott Hanselman about ASP.NET MVC wherein he explains the differences between ASP.NET and ASP.NET MVC, he is careful to point out that the users of .NET Web Forms and .NET MVC value different things. The intersection of the things that Rails and .NET MVC value is pretty large. They both value model-view separation, convention over configuration, etc. The problem with JQuery is, for me at least, to discover what it values. Maybe no one comes right out and says it often enough. Maybe articles on JQuery tend to focus more on the how than the why. I was the student in Math class that annoyed the teacher and all the other students by asking why (often, “Why do we have to learn this?”—more often than not, I got the brush off rather than an answer).

    For me, to really get behind a framework, I’ve got to understand the why rather than just the how.

    I used to look at examples of JQuery code and think, “That’s way to low-level,” or, “That looks like function soup.” I still think these things when looking JQuery code (probably because I’m used to writing object-oriented code), but now I understand there is a reason for this. JQuery folks are saying the only way to write JavaScript with an emphasis on minimalism, to reduce download times, and an emphasis on unobtrusiveness, to hopefully make pages more accessible.

    I have a concern about JQuery regarding maintenance programming. I worry about developers having to struggle to discover the intent of some JQuery code after not having touched it for an extended period of time (weeks or months). In other words, it doesn’t seem, to me at least, that JQuery code lends itself to being self-documenting.

  3. Brian said,
    on October 7th, 2010 at 12:00 pm

    @Robert:

    jQuery is difficult if you’re not used to working with languages that support closures/anonymous functions. JavaScript does it in a way that’s so close to Ruby that they’re a natural fit. jQuery is a framework for DOM manipulation, and honestly, if you don’t know how HTML, JavaScript, and the DOM work together, jQuery is going to seem insanely magical and full of maintenance nightmares. However, the reason jQuery is popular is for the same reason MVC frameworks are popular – separation of concerns. JavaScript does not belong in HTML. onclick, onblur, and onfocus attributes are just ugly, horrible, and wrong, and need to be applied as listeners unobtrusively rather than shoved into the code by a server-side html generation framework or IDE. jQuery makes it VERY simple to make that happen. Instead of putting onclick on each link, I can simply use jQuery and event delegation to watch a region of a page for clicks, then look at the event I capture and see what its target was. If it was a link, I can act on it. It actually greatly simplifies maintenance of sites for me.

    If you build things that display interfaces on the web, learn HTML, the DOM, and JavaScript. Once you’ve written your own AddEventListener function in Javacript that has to work in all browsers, you’ll move to jQuery quickly. :)

Leave a reply

:mrgreen: :neutral: :twisted: :shock: :smile: :???: :cool: :evil: :grin: :oops: :razz: :roll: :wink: :cry: :eek: :lol: :mad: :sad: