Search code examples
jqueryinternet-explorerinternet-explorer-8prototypejsconflict

jquery prototype conflict only in ie8


I'm using jQuery to build a module for an existing page. The page uses also prototype, so there is the usual jQuery-prototype conflict. I'm using the jQuery.noConflict() and everything works fine in all browsers except for ie (tested in ie8). I've read all similar questions in here and other sites, but i can't get it to work. This is about how it works: the page loads prototype and other .js files using prototype (effects.js, prototip.js etc) and then loads my module (aka jQuery is loaded after prototype). I read about changing the prototype's $() function to $$$(), but this is impossible (many other modules using prototype will then need to be changed), so it's only about changing my js.

Then i read about using

(function($) {
    //my jQuery code in here

})(jQuery);

but i don't completely understand it. My code is about like this:

$J = jQuery.noConflict();
$J(document).ready(function(){
     fun1();
     //jquery stuff
     fun2();
});

function fun1(){
     //stuff/jQuery code/ call other functions
}

function fun2(){
     //stuff/jQuery code/ call other functions
}

if i put all the above into (function($) { /*all the above*/})(jQuery);

i get that all functions are undefined.

What am i doing wrong? Or is there another solution?


Solution

  • For jQuery.noConflict(); to work it must be called before all other javascript libraries are loaded to work otherwise you'll have already overwritten the $ variable. The error you are getting with (function($) { /*all the above*/})(jQuery); is because this is defining an anonymous function, any function within this only exist within it and cannot be used outside of it, unless it is part of an object outside the scope of the anonymous function.

    So you would need to use it like this.

    //Must be called before any other library in included on the page.
    $J = jQuery.noConflict();
    
    (function($){
        $(document).ready(function(){
            fun1();
            //jquery stuff
            fun2();
        });
    })(jQuery);
    
    function fun1(){
        //stuff/jQuery code/ call other functions
    }
    
    function fun2(){
        //stuff/jQuery code/ call other functions
    }