JQuery Conflicts with Primefaces? [duplicate]

I had the same problem as described in the question. That's why I came up with the following solution:

Include the primefaces built-in jQuery library (currently 1.4.1) as including an own jQuery library leads to CSS formatting problems. Adding the target="head" attribute allows for specifying the tag everywhere - e.g. when using templating you not always have access to the <head> tag:

<h:outputScript library="primefaces" name="jquery/jquery.js" target="head" />

The primefaces jQuery library is included by default in conflict mode. That means the $() shortcut cannot by used. To overcome this issue include the following line in a <script> or <h:outputScript> tag:

<h:outputScript target="head">
    // Add the $() function
    $ = jQuery;
    // Now you can use it
    $(document).ready(function() {
        ...
    });
</h:outputScript>

That's the best solution I could dig out so far, using primefaces 2.2.1.


Why not use the jquery bundles with PrimeFaces?

<h:outputScript library="primefaces" name="jquery/jquery.js" />

PrimeFaces 2.2.1 has jQuery 1.4.4 and 3.0(in development) has 1.5.1.


Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $ . followings are some methods :

  • Write jQuery.noConflict(); before initialization of jQuery,see below

    jQuery.noConflict();
    $(document).ready(function(){
       // your jQuery code   
    });
    
  • Create a different alias instead of jQuery to use in the rest of the script.

     var j = jQuery.noConflict();
     // Do something with jQuery
     j("div p").hide();
    
  • Change all instance of $ : Replace $ with jQuery in jQuery code block

     jQuery(document).ready(function){
           jQuery("div p").hide();
     })
    
  • Completely move jQuery to a new namespace in another object.

    var dom = {};
    dom.query = jQuery.noConflict(true);
    // Do something with the new jQuery
    dom.query("div p").hide();
    
  • Set scope of $ to local instead of global

        // Method 1
        jQuery(document).ready(function($){
             $("div").hide();
        });
    
    
        // Method 2
        (function($) {
          /* some code that uses $ */ 
        })(jQuery);
    

    Note : this point comes with one drawback, you will not have access to your other library's $() method.

Original Reference