Wednesday, 22 January 2014

Jquery conflicts with other libraries like prototype.js

Most of the time when using jquery with other libraries, there will be lots of conflicts. That is because most of the libraries uses "$" as a shortcut. So when using two such libraries and calling "$" will confuses the code. I hated javascript libraries until i found that  jquery provides a nice solution for this.

The approach was explained in Jquery's official website. The solution given was, we have to put jquery in no-conflict mode.

How to put jquery in no-conflict mode:

For example you are using the following two libraries,
<script type="text/javascript" src="<%=request.getContextPath()%>/js/prototype.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-1.10.2.min.js"></script>


then immediately after loading jquery and before using it first time, add the following code,
<script >var $j = jQuery.noConflict();</script>

This will make sure that, $j will call jquery and $ will be used to call prototype. you can use any name in place $j. For example $k,$l...

Other Approach

There was another approach explained, without changing the default "$" shortcut. I have not tried this approach. Please check this if you like.

Here we have to call "jQuery.noConflict();" first and then pass the "$" in the document.ready function. And we can use "$" normally as before.

Example:
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
jQuery.noConflict();
jQuery( document ).ready(function( $ ) {
$( "div" ).hide();
});
</script>

No comments:

Post a Comment