Javascript – How to solve jQuery and mootoools conflict

conflictjavascriptjquerymootoolsplugins

I use

<script type="text/javascript" src="jquery-1.2.2.pack.js"> </script> 

to load jquery and then load an external script that contains these :


var jkpanel={
    controltext: 'menu',
    $mainpanel: null, contentdivheight: 0,
    openclose:function($, speed){
    this.$mainpanel.stop() //stop any animation
    if (this.$mainpanel.attr('openstate')=='closed')
        this.$mainpanel.animate({top: 0}, speed).attr({openstate: 'open'})
    else
        this.$mainpanel.animate({top: -this.contentdivheight+'px'}, speed).attr({openstate: 'closed'})
},

init:function(file, height, speed){
    jQuery(document).ready(function($){
        jkpanel.$mainpanel=$('<div id="dropdownpanel"><div class="contentdiv"></div><div class="control">'+jkpanel.controltext+'</div></div>').prependTo('body')
        var $contentdiv=jkpanel.$mainpanel.find('.contentdiv')
        var $controldiv=jkpanel.$mainpanel.find('.control').css({cursor: 'wait'})
        $contentdiv.load(file, '', function($){
                var heightattr=isNaN(parseInt(height))? 'auto' : parseInt(height)+'px'
                $contentdiv.css({height: heightattr})
                jkpanel.contentdivheight=parseInt($contentdiv.get(0).offsetHeight)
                jkpanel.$mainpanel.css({top:-jkpanel.contentdivheight+'px', visibility:'visible'}).attr('openstate', 'closed')
                $controldiv.css({cursor:'hand', cursor:'pointer'})
        })
        jkpanel.$mainpanel.click(function(){jkpanel.openclose($, speed)})       
    })
}
}

//Initialize script: jkpanel.init('path_to_content_file', 'height of content DIV in px', animation_duration)
jkpanel.init('1', '80px', 1000)

and also use a mootools plugin of course.

MY QUESTION IS THAT how should I use var $j = jQuery.noConflict(); in the above script to prevent conflicting

Best Answer

Wrap all the JavaScript that relies on jQuery in a closure to prevent namespace conflicts, like so:

// Start closure to prevent namespace conflicts
;(function($) {

  // Whatever code you want that relies on $ as the jQuery object

// End closure
})(jQuery);

It looks weird, but the syntax is right (yes, the first line starts with a semicolon). This automatically substitutes jQuery for the $ object, which both jQuery and mootools make use of. Since you're using both, you should wrap all of your jQuery code in a closure like this (one for each .js file or script tag).