Running jQuery alongside MooTools

For my latest project I was given the fun task of having to build a microsite modal layer for a third party website that I had no access to, not even to a dev environment.  I figured the best way to do it would be to do everything in a JS file that would inject all the html and such, so there’d no need for the mess of sending over instructions to add multiple chunks of html/css/js into various spots on the page, just the one JS call.  And jQuery was perfect for this, so I set on my merry way and coded the whole thing into a nice neat JS file, had it all working great locally, and sent it over to the clients hosting company with the simple instructions of just calling in the two JS files (the jQuery JS file and the one I’d written) into their page.  Of course rookie mistake number one – they were already using MooTools in their site, and the syntax of the jQuery and MooTools libraries totally clash.

I have no problem using MooTools and it wasn’t a lot of code so I downloaded the latest version and adjusted the syntax to match that of the MooTools library.  Of course that was rookie mistake number two – when I was done and it was all working again I remembered to check their version and it was then that I realized that they are using a fairly old version of MooTools, and the syntax was all different and I couldn’t find decent documentation to switch it out.  Of course I probably could’ve worked it out but my code was going backwards – I was all proud of my nice clean jQuery, and then it became MooTools which was okay, but now it was some funky old version of MooTools.  So I decided to switch gears and figure out how to run the two alongside eachother.

It didn’t take me long, jQuery is badass and they’ve thought of everything, there is a built-in way to run it alongside other libraries that use the same $() syntax (Prototype is another library that I can think of as well as MooTools that has this same syntax).  So consider the following:

<html>
  <head>
    <script src="mootools.js"></script>
    <script src="jquery.js"></script>
    <script>
      //mootools document ready function
      window.addEvent('domready',function() {
        //disable classic jQuery
        jQuery.noConflict();

        //do something with jQuery
        alert(jQuery(document).height());

        //do something with MooTools
        alert($(document).getSize().y);
      }
     </script>
  </head>
  <body></body>
</html>

As you can see once you run jQuery.noConflict() you can still use $() for MooTools but for jQuery you use jQuery() instead. Pretty cool huh?

That’s basically it but there are a couple more tricks. For example if you load in the jQuery library before the MooTools library apparently there’s no need to call the jQuery.noConflict() method. And also you could assign jQuery.noConflict() to a short variable name for less code. Read more here.

Tags: Javascript, Web 2.0

Leave a Reply