SiteCrafting, Inc.
How to use jQuery in a Prototype world
Managing The $ Conflict
So as we progress into a jQuery world, what are we going to do with all this old Prototype code? Well, the jQuery creator has saved the day! Below is some code that will display the results of an ajax request after the page loads.
// Resets the $ function (I suggest doing this right after loading the jQuery library)
jQuery.noConflict();
// Global variable for url of ajax request
var url = 'ajax.php';
function prototypeAjax() {
new Ajax.request(url, {
success: function(xhr) {
alert('Prototype: '+xhr.responseText);
}
});
}
function jQueryAjax() {
var $ = jQuery;
$.ajax({
success: function(data) {
alert('jQuery: '+data);
}
});
}
// jQuery Namespace
(function($) {
$(function() {
alert(url);
prototypeAjax();
jQueryAjax();
});
})(jQuery);
In the code above, there are three important things happening.
The first is the use of a global variable "url" which can still be used within a namespace. It works just like any other variable and is usable by both libraries.
The second is the normal function syntax. The jQueryAjax() function has as it's first line "var $ = jQuery;" which sets the $ function to be in jQuery mode. Now everything within that function is set to use jQuery. Any functions that are called will need that same line added if they are to use the jQuery functions.
The third important point is the jQuery namespace at the end. What this does is creates a function that takes a single parameter and names it $. Once it is created, it is immediately run and passed in the jQuery object. So, anything within that block will use the $ function from jQuery. The first line of the function sets an onload event that runs our two global functions, prototypeAjax() and jQueryAjax(). Those two functions will now use the correct $ function for their application.
What Does This Mean?
What this means is you can now start to include jQuery code into Prototype projects. Internally, we will be able to use the power and ease of coding that comes from jQuery, while not backtracking and rewriting all the old code. Bottom line: Quicker development time, lower costs, and smoother running web apps.
by Paul Sayre | 10/27/2008 12:01pm | Comments (1)
Great article - really helped, Thanks!
Left by Arjun | Sep 11, 2009