Using jQuery And Mootools On The Same Page

While it’s never a good idea to bloat your webpage with too much unneeded content, there are times when you can’t avoid it. One example I came across recently was with my day job’s adoption of jQuery as our official JavaScript framework, I needed to add some jQuery goodness to some blog pages belonging to a certain category in Movable Type. Simple, right?

Well the site in question already used Mootools extensively, so the jQuery would have to run nicely next Mootools and not disrupt existing functionality.

The designers of jQuery have designed for this sort of situation, and have provided a function called noConflict that returns the use of $ to Mootools, or any other framework you may have installed as well.

Here’s some example code to show both jQuery and Mootools running in the same page…

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript"><!--
jQuery.noConflict();
//-->
</script>
<script type="text/javascript" src="mootools-1.2-core-yc.js"></script>

In my Movable Type situation, I am able to use a custom MT tag to make sure jQuery only appears for certain categories. Let’s assume I have a category called jQuery where I need the jQuery library to be imported, the MTIfCategory tag is what I need to guard with…

<MTIfCategory label="jQuery">
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript"><!--
jQuery.noConflict();
//-->
</script>
</MTIfCategory>
<script type="text/javascript" src="mootools-1.2-core-yc.js"></script>

With this in place I can call jQuery functions using the jQuery variable, and MooTools using $ where necessary.