How to Make JQuery & Prototype Play Nice

JQuery + Prototype

I’m sure you’ve seen some of the sweetness of JQuery and most likely you’ve used Prototype for dynamic web applications like Lightview, Prototip, etc. However, let’s say we want to use the two together, on the same page. Problemo!

The Problem

JQuery uses a “$” as a shortcut for “jQuery” and Prototype uses “$” as well. We can’t have JQuery and Prototype using the same “$” namespace.

The Fix

Thankfully JQuery has a neat little function called jQuery.noConflict( ) which you basically just need to stick at the top of your JQuery file and replace the “$” alias with “jQuery” for each function. Example:

jQuery.noConflict();
// Do something with jQuery
jQuery("div p").hide();
// Do something with another library's $()
$("content").style.display = 'none';

Of course, there are other ways of solving this issue with jQuery.noConflict( ), but the method above was the most simple and straightforward for me.

NOTE: JQuery doesn’t get along with MooTools and YUI very well either, luckily this can also be solved with the jQuery.noConflict( ) trick.

Let me know if you have any questions or run across any other issues while using JQuery and Prototype. I have a feeling the more popular JQuery becomes, the more and more people will run into this issue.

Twitter Digg Delicious Stumbleupon Technorati Facebook

9 Responses to “How to Make JQuery & Prototype Play Nice”

  1. Good description of making them play nicely together. Just two things to add.

    1)

    $j = jQuery.noConflict()

    will let you use $j instead of jQuery, shorter and easier to type and

    2) Only jQuery lets you place nicely with other libraries. mooTools and Prototype do not play nicely with each other at all.

  2. @Josh – Thanks for those additions! I took a look at your blog and it looks like your an expert in JQuery – I’ll definitely be subscribing to your posts. Thanks :)

  3. You could make it even shorter with this statement:

    jQuery.noConflict();

    (function($) {

    $(“#myId”).makethings…

    })(jQuery);

    But nice blogpost for beginners who are not familiar with the noConflict method.

    Cheers.

  4. The dollar symbol spoiled my whole morning until I came across your post. Thank you!

  5. @Nirmal – I’m so happy I was able to help!

  6. Thanks! I need to mix jquery & prototype, and your short post, along with the insightful comments, make it clear and easy!

  7. I’ve noticed that you can’t use the jquery UI plugins when you have prototype. Because the plugins use the $ dollar sign.
    It would be good if we were able to change the prototype $ to use something else.

  8. @Daniel

    Uh oh! I thought all the problems are solved once for all by that magic line.

  9. @Daniel, @Nirmal – You can also change the $ dollar sign for other libraries like Prototype. Check out this link: http://docs.jquery.com/Using_jQuery_with_Other_Libraries

Leave a Reply