Wrapping functions with self invoking jQuery

Neeraj Singh

Neeraj Singh

September 3, 2009

Following code is tested with jQuery 1.3 .

I have following code which depends on jQuery.

var Search = {
  initAction: function ($elm) {
    if ($elm.attr("value").length === 0) {
      $elm.attr("value", "search");
    }
  },

  blurAction: function ($elm) {
    if ($elm.attr("value") === "search") {
      $elm.attr("value", "");
    }
  },
};

Search.initAction($("#query_term_input"));
Search.blurAction($("#query_term_input"));

Everything is cool.

Next, company decides to use a cool JavaScript widget that depends on Prototype library. After adding the Prototype library my code starts failing. I have been asked to fix my code.

I can obviously go through the code and do a mass find $ and replace $ with jQuery. This is error prone.

A better solution would be to make use of self invoking function and redefine $ to jQuery .

var Search = (function ($) {
  return {
    initAction: function ($elm) {
      if ($elm.attr("value").length === 0) {
        $elm.attr("value", "search");
      }
    },

    blurAction: function ($elm) {
      if ($elm.attr("value") === "search") {
        $elm.attr("value", "");
      }
    },
  }; // return
})(jQuery);

Search.initAction(jQuery("#query_term_input"));
Search.blurAction(jQuery("#query_term_input"));

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.