I recently discovered an amazing javascript library called jQuery by John Resig. It is so well written that it makes even those who hate Javascript (like myself) enjoy writing it. It’s philosophy is “Find things, do stuff”, and it couldn’t possibly be more true to that statement. What I love so much about it is that it can do in five lines what would have normally taken twenty.
jQuery uses the dollar sign as a function name, followed by a “query” used to “find things” to “do stuff” to. The problem with this is that other widely used javascript libraries use the dollar sign for their function names as well. One such library is Prototype. Prototype uses the dollar sign as a shortcut to document.getElementById. So, when I need to use both JQuery and Prototype, what do I do? Well, jQuery has provided a handly little method called noConflict() to deal with just such an issue. To remedy an issue where the dollar sign function names conflict, you simply assign Jquery.noConflict() to something such as $j and then use that instead of the dollar sign.
Before:
$("#product_attributes img").click(function(){ $(this).parent().prev().children('input:radio').focus() .attr("checked", "checked"); }) .css("cursor", "pointer");
After:
var $j = jQuery.noConflict(); $j("#product_attributes img").click(function(){ $j(this).parent().prev().children('input:radio').focus() .attr("checked", "checked"); }) .css("cursor", "pointer");
Further Reading
jQuery’s documentation for JQuery.noConflict()
Christopher Hlubek Says:
May 8th, 2007 at 1:32 am
Thanks for the good explanation. It just works
Giovanny Gutierrez Says:
June 6th, 2007 at 11:27 am
Thank you for this… tip… was working on it for a while trying to break my head up!
Luke Visinoni Says:
June 6th, 2007 at 11:53 am
Glad I could help!
Sean Says:
September 4th, 2007 at 3:57 am
Why not just use “jQuery(’#…’)” and remove the cryptic $ from the code all together?
Luke Visinoni Says:
September 4th, 2007 at 7:40 am
No reason. That will work just fine.