How to write your own JQuery Plugin

Dont repeat yourself – DRY – and write your own JQuery plugin for that piece of code that you reuse a lot of time in your projects.

Creating a simple Highlight Plugin

In this small example we are going to create a plugin that highlight an element. It simply changes the background and font-style css properties.

The first thing we have to do is to be sure that our plugin runs inside a local scope by wrapping out all your code inside of an Immediately Invoked Function Expression (IIFE):

// Plugin basic structure
(function($) {

    $.fn.yourMethod = function() {

        // Your Method code

    }

}(jQuery));

In the IIFE you pass the function jQuery as a parameter called $ in order to avoid collission with other Javascript Libraries. With the use of self-closed javascript pattern you are sure that all your variables are outside of the global namespace.

Now we have created our local scope, the second thing is to add your methods to jQuery.
It’s time to meet the jQuery $.fn object, the object that contains all of the jQuery object methods and it allows to add your as well.

If with your plugin you want manipulate some DOM elements, you need to use .each() method to loop through the elements.

(function($) {

    $.fn.highlight = function() {

        this.each( function() {
            $(this).css ({"background": "yellow","text-decoration": "underline"});
        });

    }

}(jQuery));

Let’s see how to use our plugin:

<script>
$(document).ready( function() {
    $('h1').highlight();
});
</script>

We have not finished yet, we have to make our plugin method chainable by returning the object itself.

(function($) {

    $.fn.highlight = function() {
        return this.each( function() {
            $(this).css ({"background": "#ffff00","text-decoration": "underline"});
        });
    }

}(jQuery));

Our First Plug-in is done!

Now let’s see how to add options to our plugin with some defaults options.

(function($) {

    $.fn.highlight = function( options ) {
        // Creating a settings object and extend it with the options
        var settings = $.extend({
            color        : "#ffff00",
            fontStyle    : "underline"
        }, options);

        return this.each( function() {
            $(this).css ({"background": settings.color,"text-decoration": settings.fontStyle});

        });

    }

}(jQuery));

Example of use:


$('h1').highlight({
    color       : '#ffff00',
    fontStyle   : 'underline'
});

Now let’s see how our plugin can handle callback! We pass the callback as option, for instance as a complete option.
Before to invoke it, we have to check with $.isFunction that is a function and not for example a simple string.

(function($) {
    $.fn.highlight = function( options ) {

        var settings = $.extend({
            color        : "red",
            fontStyle    : "underline",
            complete    : null

        }, options);

        return this.each( function() {
            $(this).css ({"background": settings.color,"text-decoration": settings.fontStyle});
            // Callback Management
            if ($.isFunction(settings.complete ) ) {
                settings.complete.call( this );
            }
        });

    }

}(jQuery));

Let’s see how to use:

var hightlightCompleted = function () {
		console.log('Highlightdone');
	}

	$("h1").highlight({"color":"#FFFF00","fontStyle": "italic", "complete":hightlightCompleted});

Leave a Reply

Your email address will not be published. Required fields are marked *