Playing Interference with jQuery and Prototype

Posted: April 28, 2011 in JavaScript

Lately I’ve had to deal with jQuery conflicting with Prototype.

For starters I was forced to upgrade from jQuery 1.4.2 to 1.5.2 to fix a conflict when doing clones.

But of course there’s always the ‘$’ conflict. So I wanted to come up with a slick way of keeping the ‘$’ alias available for use by jQuery code.

For starters the existing code looks like this:

<script src="prototype.js" type="text/javascript"></script>
<script src="jQuery.min.js" type="text/javascript"></script>
<script type="text/javascript">
	jQuery.noConflict();
	jQuery(document).ready(function(){
		/* js code here */
	});
</script>

The ‘jQuery.noConflict()’ statement kills off the jQuery ‘$’ alias for me. So to have ‘$’ available for my use I wrapped everything around a Self-Invoking Anonymous Function looking like this:

(function( $ ) {
	$(document).ready(function() {
		/* js code here */
	});
})(jQuery);

https://gist.github.com/firefighter990/5340332

Notice that the jQuery object is now being passed in via the $ argument inside a JavaScript closure. Thus everything I do inside the closure will not conflict with any other library.

Advertisements
Comments
  1. Daniel List says:

    Thanks so much for this.. I was fighting with conflicting libraries for hours and your little enclosing snippet sorted it all out for me.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s