Using Self-executing Functions to Preserve Dollar Sign compatibility in JQuery

This is a very simple concept and is mostly common knowledge but I recently came across a need to use it fairly extensively and figured I would share. At my place of work we decided to adopt JQuery as our javascript framework. The problem we had is that the application we were maintaining made grotesque usage of another javascript framework called MooTools. MooTools also uses the dollar sign ($) for many of its calls and this caused the library to conflict with JQuery. Luckily JQuery is awesome and with one call to jQuery.noConflict(); you can make JQuery compatible with other libraries by preventing it from accepting the dollar sign.

The thing that sucks about noConflict() is that after you call it you can't use the dollar sign anymore. Now with this little trick, you can. You create a self-executing function and you pass in the jQuery object and make the variable inside the function signature be a dollar sign.


(function ($) // Self-executing function {
    $(function () {
        $('<div></div>') // Do awesome JQuery stuff
            .text('My beloved dollar sign is back!!!')

Basically what you're doing is defining a function and calling it at the same time. You define the function within parenthesis:

(function ($) {
    // my function

After you define the function you immediately call it by including a second set of parenthesis. If your defined function accepts any parameters then you pass them in here:

(function ($) {
    // '$' is an accepted parameter.
    // 'jQuery' is the object being passed into this function.
    // You essentially turn jQuery into $ for the scope of this function.

It's such a simple little trick, and all properly written JQuery plugins use this to ensure they remain compatible with other libraries. This handy little feature has allowed me to continue my habit of writing JQuery code with the dollar sign, even though noConflict() has been called.


Read more posts by this author.

comments powered by Disqus