Alex
Alex

Reputation: 68492

jQuery - function conflicts

I have a WordPress theme and I'm using a few jQuery plugins within it. The problem is that some of these plugins are included in other WP plugins, so the js breaks because of naming conflicts.

I was wondering if there is a way to somehow isolate a set of functions or a .js file from the rest of the scripts that are being included in the HTML document.

something like:

function wrap(){

  plugin functions...
  plugin functions...

}

jQuery(document).ready(function($){
   wrap.pluginfunction()...
   wrap.pluginfunction()...
});

Upvotes: 0

Views: 917

Answers (2)

cdhowie
cdhowie

Reputation: 169018

The easiest way to do this is to wrap the whole script like this:

var someNewNamespace = (function () {
    // Script goes here

    // If you want to expose functions on the namespace:
    var that = {};

    // Declare a new function to expose:
    that.someFunction = function () {
        // ...
    };

    // Expose a function declared previously:
    that.someOtherFunction = someFunctionDeclaredPreviously;

    return that;
}();

This will effectively create a new namespace for the script. The someNewNamespace object will have members like someFunction etc. after this executes. Any variables declared within the anonymous outer function, but not exposed via the that object will be inaccessible from outside of the script.

Upvotes: 2

Wolph
Wolph

Reputation: 80031

jQuery has a noConflict() method so it won't kill other libraries.

Just call jQuery.noConflict(); after loading the jquery library and you should be set.

Upvotes: 1

Related Questions