pirmdiena, 2011. gada 14. novembris

How to use jQuery noConflict() method

Hello, I'd like to share my idea on how to use jQuery's noConflict method in an environment where other JavaScript libraries are used. In case You don't know what this method is for, I can tell that it's used to make sure that jQuery's global object named '$' doesn't override variables with the same name in global JavaScript scope. If You wan't a more detailed description, you should read the documentation here.
Nevertheless, here's the code:

jQuery.noConflict();
( function ( $ ) {
    $(document).ready( function () {
        // use $ object as usual, for example
        $('#animated').delay(3000).show('slow');
    });
} ( jQuery ) );

The trick here is that after calling jQuery.noConflict method, the global object 'jQuery' is passed to an anonymous self-calling function, which can further use the global jQuery variable ( $ ) as usual without worrying about polluting the global scope. Using this approach existing JavaScript code that uses jQuery library can be safely ported to an environment where other libraries like mootools or prorotype are used.