Advertisement

Learn How to Create a jQuery Plugin

by

You might think to yourself, "What is all the fuss with jQuery? You have to download a bunch of plugins to even make the library worth while.". First, that isn't true. Second, the jQuery library was specifically designed for that very purpose. By keeping the core library as small as possible - about 16 kb - users can then apply additional plugins at their own discretion. Today, I'll teach you how to build your first "Center" plugin from scratch. Let's get started!

Our Objective

We want to create a plugin that will dynamically adjust the styling of a specified element in order to keep it vertically and horizontally centered on the page at all times - even when the browser window is resized. Very little is required up front. You only need to make sure that you have the jQuery library downloaded.

The Screencast

Step 1

The first step when creating a plugin is to add a blank Javascript file. Naming conventions state that the file should be named "YourPluginName.jQuery.js". Once you've created this file, make sure that you create a reference to it in your document.

<head>
    <script src="jquery-1.2.6.pack.js" type="text/javascript"></script>
    <script src="center.jQuery.js" type="text/javascript"></script>
</head>

Step 2

Next, paste in the following code.

(function($){

$.fn.center = function(){

var element = this;

$(element).load(function(){

changeCss();

$(window).bind("resize", function(){
    changeCss();
});

function changeCss(){

    var imageHeight = $(element).height();
    var imageWidth = $(element).width();
    var windowWidth = $(window).width();
    var windowHeight = $(window).height();

    $(element).css({
        "position" : "absolute",
        "left" : windowWidth / 2 - imageWidth / 2,
        "top" : windowHeight /2 - imageHeight / 2
    });
};
});

};

})(jQuery);

I go into much greater detail in the video, however, I'd still like to go over a few key points. Any time that you create a plugin, it must be wrapped with:

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

"Center" should be replaced with whatever your plugin's name is. This lets jQuery know that you're extending its methods. Now, though it does absolutely nothing, we can call our center method with:

$(function(){
  $("#someElement").center();
});

Step 3

You must understand how to manually center an image on a page before creating the plugin. First, your element must be positioned absolutely. Otherwise, it obviously won't budge when we alter the "left" and "top" values. Next, the image needs to be shifted 50% of the browser's width to the left. Finally, in order to compensate for the image's width, we need to subtract one half of the image's width.

function changeCss(){
    var imageHeight = $(element).height();
    var imageWidth = $(element).width();
    var windowWidth = $(window).width();
    var windowHeight = $(window).height();

    $(element).css({
        "position" : "absolute",
        "left" : windowWidth / 2 - imageWidth / 2,
        "top" : windowHeight /2 - imageHeight / 2
    });
  };

This will perfectly place the center of the image in the center of the page. It's a bit hard to explain with text. Be sure to watch the video for a greater explanation.

Step 4

Continuing on, we need to create a listener for when the browser window is resized.

$(window).bind("resize", function(){
    changeCss();
});

"ChangeCss()" is a function that adjusts the left and top values of our image. By calling it again when the window is resized, jQuery will recalulate those values.

You're Done!

If you have any questions, please feel free to leave a comment and I'll make sure that I respond. As always, this might not be "real world ready". What happens if the user has Javascript turned off? And of course, there are some ways to do this using pure CSS - but I digress.

Subscribe to the Weekly Screencasts

You can add our RSS feed to your ITUNES podcasts by doing the following:

  1. Once ITUNES has loaded, clicked the "Advanced Tab"
  2. Choose "Subscribe to Podcast"
  3. Enter "http://feeds.feedburner.com/NETTUTSVideos"

That should do it! The screencast will also be searchable on ITUNES in the next twenty four hours.

  • Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.


Advertisement