Just a {code} blog

Creating your first JQuery plugin

When you are working with large projects, sometimes you may need to reuse existing pieces of code again and again. Copying-pasting your functions or html blocks is one way to do it but this is not what DRY dictates.

With Jquery you have an option to reuse your code with plugins.

Jquery plugins is the acceptable way to share your code within multiple webpages or even projects. For our tutorial will we will be creating a basic "Hello World" plugin. Let's start with the skeleton of our plugin:


(function ( $ ) {
 
    $.fn.hello = function() {
      
        return this;
    };

}( jQuery ));

Here we put all of our code inside of an immediately invoked function expression and we are making our code accessible with the function

hello
Now, for our tutorial we will be making something simple, an input box and a button. When the user will click the button, the plugin will popup an alert dialog displaying the contents of the input box. Real simple!

Let's fill in the empty spaces within the hello function:


(function ( $ ) {
 
    $.fn.hello = function() {
      	this.append('< input type="text" id="helloInp">< button type="submit" id="helloBtn">Hello');
        
        this.each(function(){
          var $input = $(this);
          var helloButton = $input.find("#helloBtn");
          var helloInput  = $input.find("#helloInp");

          helloButton.on('click',function(e){
              alert(helloInput.val());
          });
        });
        
        return this;
    };

}( jQuery ));

Let's break down what we did here. First we append inside the div or somewhere else the input box and the button. Then we scan for those DOM elements with the

.each()
function and bind the click event to the our button. When the button is clicked, the alert dialog will display the contents of the input box.

The contents of the plugin can be saved inside a separate file, hello.js and can be loaded like any other js file.

Now it's time to load our elements inside our page and especially inside a div. Our code would look like this:


$( "#hello" ).hello();

This line is telling our page to load the hello function and since we are adding elements (via append), to load them inside the div with id "hello".

This is a very simple tutorial, showing only the basics but it's a starting point for creating more complex and optimized plugins.

The code for this tutorial can be found here (Github).