Wrapping functions with self invoking jQuery

Neeraj Singh

By Neeraj Singh

on September 3, 2009

Following code is tested with jQuery 1.3 .

I have following code which depends on jQuery.

1var Search = {
2  initAction: function ($elm) {
3    if ($elm.attr("value").length === 0) {
4      $elm.attr("value", "search");
5    }
6  },
7
8  blurAction: function ($elm) {
9    if ($elm.attr("value") === "search") {
10      $elm.attr("value", "");
11    }
12  },
13};
14
15Search.initAction($("#query_term_input"));
16Search.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 .

1var Search = (function ($) {
2  return {
3    initAction: function ($elm) {
4      if ($elm.attr("value").length === 0) {
5        $elm.attr("value", "search");
6      }
7    },
8
9    blurAction: function ($elm) {
10      if ($elm.attr("value") === "search") {
11        $elm.attr("value", "");
12      }
13    },
14  }; // return
15})(jQuery);
16
17Search.initAction(jQuery("#query_term_input"));
18Search.blurAction(jQuery("#query_term_input"));

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.