Write Your Own jQuery Plugin

Writing your own jQuery plugin isn't as hard as it might seem at first. This article shows the process of writing a simple plugin, adding some options and even performing a callback.
 
Plugin declaration

Here is the simple syntax to get started declaring a jQuery plugin:

(function ($) {

  $.fn.hello = function () { /* code goes here */ }

  } (jQuery));
 
In this I have used "$.fn"; this is the shortcut of "jQuery.prototype".

The problem we have here is that the $ syntax could conflict with other JavaScript libraries. An easy way to overcome this problem is by wrapping your jQuery plugin inside a self-invoking anonymous function. An anonymous function is a function without a name that is executed immediately. You can call the function with jQuery as the argument and $ as a parameter allowing you to use the $ syntax in a safe manner.
 
An example will clarify that.

index.html file
 

<head>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">

    </script>

    <script type="text/javascript" src="jquery.hello.js"></script>

    <script type="text/javascript">

                          $(document).ready(function () {

    $("#first").changeBgColor(); // calling the custom function

});

    </script>

</head>

<body>

    <div id="first">

        This is the basic plugin development<br />

    </div>

</body>

<html>
 
jquery.hello.js file
 

 (function ($) {

    $.fn.changeBgColor = function () {

        console.log("hello");

        $(this).css({

            'backgroundColor': '#ff0000',

            'color': '#fff'

        });

    }

} (jQuery));


In the js file we have made a custom function for changing the background color using the CSS function of jQuery.

"this" represents the element that we have passed in html as $("#first").

You can use any function and make your own plugin.
 
Here are the screenshots of the development of the plugin.
 
index.html

jQuery-Plugin-1.jpg
 
jquery.hello.js

jQuery-Plugin-2.jpg

Output

jQuery-Plugin-3.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all