---
title: "Wrapping functions with self invoking jQuery"
description:
  "Wrap your function with self invoking jQuery instead of performing
  find/replace."
canonical_url: "https://www.bigbinary.com/blog/wrap-your-function-with-self-invoking-jquery-instead-of-performing-find-replace"
markdown_url: "https://www.bigbinary.com/blog/wrap-your-function-with-self-invoking-jquery-instead-of-performing-find-replace.md"
---

# Wrapping functions with self invoking jQuery

Wrap your function with self invoking jQuery instead of performing find/replace.

- Author: Neeraj Singh
- Published: September 3, 2009
- Categories: jQuery

_Following code is tested with jQuery 1.3 ._

I have following code which depends on jQuery.

```javascript
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](understanding-jquery-plugin-pattern-and-self-invoking-javascript-function)
and redefine `$` to `jQuery` .

```javascript
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"));
```

## Links

- [Human page](https://www.bigbinary.com/blog/wrap-your-function-with-self-invoking-jquery-instead-of-performing-find-replace)
