5 Things to Know When Migrating Prototype to jQuery

2 Comments

I just finished moving 1000+ lines of javascript from Prototype to jQuery. At first it went slow, but after a while it went relatively fast because the code was pretty basic. In the end, there were only 5 things that I needed to “translate”.

Prototype adds methods to the internal Javascript classes, while jQuery simply provides and a new function jQuery and a new type of object, the jQuery object, but otherwise Prototype and jQuery appear very similar. Both use the “$” in their syntax, but I prefer the alternate “jQuery” syntax below.

1. Selecting DOM elements

Prototype’s selector returns DOM elements.

$(element_id) => DOM element

jQuery does not.

jQuery('#'+element_id) => jQuery object which may include 0-n DOM elements.

jQuery('#'+element_id)[0] => first(and likely only) DOM element

The one gotcha is remembering when you’re dealing with a jQuery object or a DOM element.

2. Binding functions to contexts

Prototype has a bind function.

function.bind(context)

jQuery binds with a proxy.

jQuery.proxy(function, context)

3. Iterating over an array

Prototype adds an each method to Array.

Array.each(function(item){ ... })

jQuery can iterate over arrays.

jQuery.each(Array, function(item){ ... })

But usually you want to iterate over the results of a jQuery selector:

jQuery(".className").each(function(index, element){ ... })

4. Adding event handlers

Prototype adds the observe method to DOM elements

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

jQuery has the bind method.

jQuery('#'+element_id).bind("click", function(jQueryEvent){ ... })

…or the shorthand click (and others).

jQuery('#'+element_id).click(function(jQueryEvent){ ... })

The jQueryEvent object is not the same as a regular event object, but target() both work the same.

5. On DOM Ready

Initializing on DOM ready is done with Prototype’s observe method as:

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

In jQuery:
jQuery(function(){ ... })

I’m not a Prototype or jQuery expert, so your milage may vary. I’m mostly writing this for the next time I have to migrate Prototype to jQuery.

2 Comments (+add yours?)

  1. Ypl
    Feb 18, 2014 @ 23:34:39

    Thanks a lot for this article !
    It helped me a lot when trying to write an automated code to migrate from prototype to jQuery.

    I’d like to notice 2 things I changed : jQuery.bind method is now .on
    And I also added automatic migration from .value to .val() and .value = anything; = .val(anything);

    Reply

  2. Josef
    Jul 17, 2014 @ 00:30:45

    I see a lot of interesting articles on your website.
    You have to spend a lot of time writing, i know how to save you a lot of work, there is a tool that creates unique, SEO friendly posts in couple of minutes, just type
    in google – k2 unlimited content

    Reply

Leave a Reply