Try Tuts+ Premium, Get Cash Back!
Create A jQuery Plugin
videos

Learn How to Create a jQuery Plugin

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 src="center.jQuery.js" type="text/javascript">
</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.


Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Kidd Lee

    Can anyone please show me a working example of how to get this done in DIV? thanks a lot!

  • http://www.jonathansace.com John

    Is there’s a DIV sample using this tutorial? I think this is VERY USEFUL if we can make it using DIV.

  • Yosi

    I can’t see the video,
    When I start the video I see the video of the jFlow Plugin and not how to create a plugin.

  • Pingback: Создаем плагин для jQuery

  • playinlife

    I can’t see the video too…

  • Pingback: jQuery Tip: Resources for Creating Your Own Plugins | Dev Tips | Become a Better Developer, One Tip at a Time.

  • http://www.norabrowndesign.com Nora Brown

    Confused…if “this” is already a jQuery object, and you then assign that object to the variable “element”, why do you need to wrap it as in “var imageHeight = $(element).height();” ? Why not just element.height(), which does seem to work at least in Safari and Firefox?

  • http://jquery-howto.blogspot.com jQuery Lover

    @Nora:
    Because “this” is a DOM object and $(this) or $(element) is a jQuery object and this object has height() method in it.

    You can read more about jQuery custom functions and custom plugins here.

    You might find this useful as well. All jQuery plugins related posts: http://jquery-howto.blogspot.com/search/label/plugin

  • Sam

    I am not able to see this video

  • http://www.kalyanonline.blogspot.com calyan Kumar

    hey! that stuff was really helpful. I have developed a sample plugin. Now where can i make it available to others?

    • http://zreedee.com Luis

      Create an account in GitHub and share :)

  • http://www.sponsormark.co.uk Mark

    Ok so this is pretty cool, a nice example of how to create a plugin.

    However, the functionality of this is useful to me. How can I adapt this to center the image within a div, not the browser window?

    The div will be a set width/height and the image within it will vary in size but need to stay centered..?

    There is examples out there in google but appear to be quite clunky..

    Many thanks

  • Pingback: Några jQuery plugins | qvister

  • Eyveneena

    I have been studying jQuery for about two years now and I was to the point whenever rewriting a set of code that I usually use became tedious I thought “maybe it is time to learn how to turn this into a function?” I ran across this tutorial creating a plugin. Plugins are for the “pros”. This was explained and I realized that I understood more than I thought I would about a basic plugin. So, I will attempt to make a plugin. Anyway, this was truely enlightening to the core idea of creating a plugin. Not sure what I am getting into. LOL
    Thank you.

    PS. are you using sql software to create this?

  • Eyveneena

    I did it! I did it! I did it! I built my first plugin! It works OMGoodness!
    Thank you soooo much for this tutorial! And I used Visual Web Developer to do it!

  • Kees C. Bakker

    Nice tutorial. One suggestion though. If you want to position the image in the middle of the window you’ll need to use ‘fixed’ as the css position. When you use ‘absolute’ it gets position to the first element that not is fixed (by default all elements are fixed).

    Normally this won’t be a problem, but sometimes you have a parent element that has a relative or absolute position. For more info on positioning look at http://www.w3schools.com/Css/pr_class_position.asp.

    Keep up the good work!

  • http://www.indialike.com indialike

    Very nice and useful tutorials for web designers,
    Thanks for posting.

  • Pingback: Lightbox con jQuery (v2) « ixmael.ar+s

  • varun

    excellent screen cast! just what I was looking for.

    thanks a lot.

    you rock!

  • http://www.amirfadaee.com Amir H Fadaee

    Hi

    How to create plugin, for ” sortArray”!?

    can U help me?

  • http://www.swapnilvathare.com Swapnil

    Hi Jeffrey
    Very nice plugin
    but it’s not working for firefox, so i have done some change in plugin and now its working.

    here is new code
    YOUR CODE
    (function($){

    $.fn.center = function(){

    var element = this;

    $(document).ready(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);
    .

  • Dhiraj Laddha

    Hi Jefferey,

    I have more the one image tag then How will work on all images this plugin because currently it just center only single image properly but not all images.

    example: such as I have one image large as your example image and another image is small icon but it not come in proper center.

    Do you have any idea regarding my problem?

    —-
    Thanks
    Dhiraj Laddha

  • elmadito

    cool tutorial

  • Saurabh

    Hi,

    How to run jquery plugin code.

  • http://www.heronote.com heronote
  • http://www.heronote.com heronote

    Free jQuery & jQuery UI eBook:

    http://www.heronote.com/files/jQuery.htm

  • http://www.weebuild.biz Nathan

    Thanks for this tutorial!

    But, how can I make “defaults” or “options”? I would like to do something like this:

    $(‘#id’).pluginName({
    ‘option1′ : ‘setting1′,
    ‘option2′ : ‘setting2′,
    ‘option3′ : ‘setting3′,
    ‘option4′ : ‘setting4′
    });

    How can I do this?

    Thanks in advance,
    Nathan

  • Pingback: 30+ Best JQuery Tutorials | 1 step web design

  • http://www.admecindia.co.in Ravi Bhadauria

    I think this is not cross browser example.

    I have tested on ie8, the object is not in center.

    Thanks
    admec multimedia

  • http://www.forzaxlr8.com/ Forza xlr8

    You actually ensure it is seem very easy along with your presentation but I find this topic to become really a thing that I think I’d never understand. It seems too complicated and extremely broad for me. I’m anticipating for your forthcoming post, I will try to get the hang of it!

  • http://fatherofthebrideweddingspeech193tip.wetpaint.com/page/Example+Father+of+the+Bride+Speeches+-+10+recommended+Tips+to+actually+Follow Raquel Caprario

    Definitely imagine that that you stated. Your favorite reason seemed to be at the web the easiest thing to be mindful of. I say to you, I certainly get irked whilst folks think about worries that they plainly do not understand about. You controlled to hit the nail upon the top and also defined out the entire thing without having side effect , other folks could take a signal. Will likely be again to get more. Thanks

  • vivek

    i hate jquery because its not allowing me to learn javascipt.whenever i google how to make a plugin with javascript alone. it shows result for making a plugin with jquery.please help me by showing correct refrences to learn javascript except books.(i know everyting about basics in javascript)

  • Domonique

    You don’t need script to put divs or images centered on a page anymore. You can just use css with a flow layout.

  • Pingback: Jquery naming convention | GeekFreak

  • Pingback: 30+ Best JQuery Tutorials | ThemesPress

  • carine

    thanks..this is an awesome tutorial!

    • Gabriel

      Muy bueno!

  • http://twitter.com/jeff_pz_cr Jeffrey Briceno

    Jeff using windows!!! this tut is very old, but is a great tutorial thk