Coding a simple jQuery centering plugin

There are quite a few tutorials out there on how to make plugins for jQuery. Quite a few of those tutorials cover how to make a plugin that centers an element within another one.

This tutorial will recap some plugin development basics, as well as add a bit more utility to our center plugin.

Step One: The shell of a jQuery plugin

Every jQuery plugin should be wrapped in a closure like so:

(function($){
//plugin code here
})(jQuery);

This anonymous function allows us to have variables in a private scope that matter to our plugin and only our plugin. Since the anonymous function is invoked right away and passed the window’s jQuery object, which we pass in as the famous dollar sign, we don’t have to worry about any naming conflicts.

Step Two: jQuery.fn—the place to plugin

jQuery provides a place to add functions to the jQuery object. This place is jQuery.fn. Any properties you add as functions to this, will be available to jQuery. To make a center function that will allow something like $(‘#myelem’).center(), we set our plugin up like so:

(function($){
    $.fn.center = function(options) {
    };
})(jQuery);

You will notice we create an argument for our function called options. This is a great way for people to pass in configuration options for the plugin. Let’s set up our center plugin.

Step Three: Setting up the center plugin

Let’s set up our default options, and the functions we will need to handle the centering:

(function($){
    $.fn.center = function(options) {
        //keep your var declaration count down
        var defaults = {
            type:'both',
            //this could be body,a selector, the window, whatever floats your boat
            container:$('#container')
        },
        //this refers to the current jQuery object i.e $('#myelemtocenter')
        elem = this,
        //our helper function to center vertically
        vert = function() {
            elem.css("top", ((options.container.height() - elem.outerHeight()) / 2) + options.container.scrollTop() + "px");
        },
        //our helper function to center horizontally
        horiz = function() {
            elem.css("left", ((options.container.width() - elem.outerWidth()) / 2) + options.container.scrollLeft() + "px");
        }
    };

    //finally we map our defaults and any options that override them
    options = $.extend({},defaults,options);
})(jQuery);

Step Four: Let’s center some stuff

It’s as easy as looking at our options and reacting accordingly:

(function($){
    $.fn.center = function(options) {
        var defaults = {
            type:'both',
            container:$('#container')
        },
        elem = this,
        vert = function() {
            elem.css("top", ((options.container.height() - elem.outerHeight()) / 2) + options.container.scrollTop() + "px");
        },
        horiz = function() {
            elem.css("left", ((options.container.width() - elem.outerWidth()) / 2) + options.container.scrollLeft() + "px");
        }
    };
    options = $.extend({},defaults,options);

    //set the position to absolute
    this.css('position','absolute');
    //if you like, set the parent position to relative
    //personally, I would save this for a stylesheet
    //this.parent().css('position','relative');

    //check the options and use the helpers!
    if ( options.type === 'horizontal' ) {
        //just center horizontally
        horiz();
    } else if ( options.type === 'vertical' ) {
        //just center vertically
        vert();
    } else {
        //center both vertically and horizontally
        horiz();
        vert();
    }
    //always return this to maintain the ability to chain
    return this;
})(jQuery);

Step Five: Use that plugin!

Using the center plugin is really easy!

//center vertically and horizontally in the default container
$('#box').center();

//center vertically and horizontally in the body
$('#box').center({
    container:$('body')
});

//center just horizontally in the main div, then change the background color
$('#box').center({
    type:'horizontal',
    container:$('#main')
}).css('background','red');

Hopefully this tutorial gave you a good head start on plugin development in jQuery, and hopefully will provide a handy little tool to use in your projects.