Posted 11.25.2009

Updated 02.28.2015

Writing jQuery Plugins (Part 1)

The more I write code, the more I realize how repetitive it is. It’s more cost effective (and brain-thawing), if you can figure out ways to be reuse your code. A few weeks ago, I started trying to figure out how to write my own jQuery plugins. Granted, you can probably find an existing plugin for anything that catches your fancy, however, a lot of times, the footprints are larger than necessary to accommodate more people. Besides, I’ll usually find one effect and stick to it (personal preference), rendering most of the customization in the plugin useless. At this point, it becomes easier to write my own code.


Here are a few sites that I looked at to help me get a grasp on structure. As most things, some are better than others. The hard part is some people assume you know more or less, leaving you to put the pieces together. My goal, in this post, is to the heavy lifting for you.

First things First

I’m gonna assume that you’ve at least heard of jQuery. If not, the elevator pitch? It’s a framework for JavaScript. In my humble opinion, it’s far easier to understand and much easier to write than JavaScript. If you’re a web developer, it’s definitely something worth checking out. I’d start by visiting the jQuery site or I’ve listed a few books (yes, you read that correctly, books) at the bottom of this post.

Captain Obvious

The first thing you’ll need to do is download the jQuery library. This has to be included on your page before any jQuery code can be written.

<script src="js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script> 

Update February 28, 2015

One of the things I prefer to do is use Google’s CDN version of jQuery. Several reasons:

  • It prevents me from having to download the code and store it on my server.
  • If your user has visited another site that is using Google’s CDN version of jQuery, then their computer will cache the code on their computer. Then, when that same user visits your site, the code is already cached and it’s one less thing they will need to download to get your site to load.

Instead of using the above line, you can use this instead:

 <script src=""></script>

Digging In

File Naming Structure

Your file should always be called jquery.your_plugin_name.js. Obviously, your_plugin_name will be unique to your plugin.


Yes, documenting your code is a pain. However, I promise, when you come back to your code, months later, it more than pays off. The code that you say (and wish) you will never come back to will inevitably haunt you. (can you hear the agony of experience in my voice?) :-) Besides, plugins are meant to be reused.

At the top of my file, I list out the name of the plugin, the date that I wrote it, the author (me!), my url, requirements, and implementation.

/* ==================================================================
*    DATE:                 FEBRUARY 28, 2015
*    AUTHOR:             AMY HAYWOOD
*     URL:                 WWW.AMYHAYWOOD.COM
*    REQUIREMENTS:         jQuery
*                        Be sure to include the jQuery library before including this script
*        Within the $(document).ready(); all that you really need to include is:
*        |    $('.CLASS_NAME_FOR_ROLLOVER').rollover();
*        Within your HTML, be sure to give the image, use the same classname that you used to call .rollover()
*        Within the rel attribute, include the path to the rollover image
*        |    
===================================================================== */

Code within your plugin

Basically, every plugin that you will write, will have the following code in it.

(function($) {
    $.fn.rollover = function(options){
        var defaults = {};

        var settings = $.extend(defaults, options);

        return this.each(function() {


Let’s take a step back…



  • I want to have an image with the file path of the rollover in the rel attribute.
  • When the user rolls over the image, it is swapped out with the value provided in the rel attribute.
  • When the user rolls off the image, it is swapped back to the original image.

Easy enough?


If I didn’t plan on using this code again, I would simply put the following code in the $(document).ready(); code in my header.

$(document).ready(function() {
    $('img[rel]').each(function() {
        var curImg = $(this);
        // GET THE VALUES
        var defaultImage = $(curImg).attr('src');
        var rolloverImage = $(curImg).attr('rel');
        $(curImg).hover(function() {
            $(curImg).attr('src', defaultImage);
        }, function() {
            $(curImg).attr('src', rolloverImage);

Too much too fast? No worries. I’ll break it down.

When you write jQuery code, most of it will appear within $(document).ready();. Basically, it waits until all the pieces on your web page have loaded and are available.

In this example, if we tried to find all the images before they had even loaded, it would return nothing!

$('img[rel]'.each(function() { 

This line of code looks for every image with a rel attribute. For EACH item, it will grab the current image src $(curImg).attr(‘src’) and save it as defaultImage. Then, it will grab the path for the rollover image $(curImg).attr(‘rel’) and save that as rolloverImage.

Lastly, it will set up the behavior. The hover function takes two parameters. The first, will determine what happens when you rollover the item and the second parameter will determine what happens when you roll off. In this case, it’s just a matter of setting the img src based on the defaultImage and rolloverImage.


Basically, we take the code that we would have made for 1 site and plug it into our jQuery plugin structure. The hardest part is just making sure we abstract everything (a.k.a. make it generic enough so that we can use it over and over).

(function($) {
    $.fn.rollover = function(options){
        var defaults = {};

        var settings = $.extend(defaults, options);

        return this.each(function() {
            var $element = $(this);
            var defaultImage = $element.attr('src');

            $element.hover(function() {
                $element.attr('src',  $element.attr('rel'));
            }, function() {
                $element.attr('src', defaultImage);


The only thing that I changed was I took out the code that was in the .each() function (from my 1 site code) and placed it within the this.each(function() { }); of the plugin. Now, when I call the plugin, it will run the loop on all the items I pass to it.

So, in the header of my HTML file, it will look like this:

    <title>JQUERY ROLLOVER TEST</title>
    <script src="js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="js/jquery.rollovers.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript" charset="utf-8">
        $(document).ready(function () {
            // INITIALIZE PLUGIN

Now, for every item in the body that has a class name of .CLASS_NAME_FOR_ROLLOVER it will try and create a rollover.

Stay Tuned

This post would probably fit into the “assuming you know less” category. On Friday, I’ll take a more in depth look at plugins, demonstrating their extensibility (i.e. setting preferences). Just to whet your appetite, we’ll be building an image rotator where you can pass in the speed.

Download My Code

jquery.rollovers.js (kB)


Call me old fashioned, but I still enjoy reading programming books. I know, ancient. I love my Kindle, but there is still something to be said for flipping pages, laying out multiple books, and cross-referencing. With that said, my favorite jQuery resources are books. That’s how I taught myself.

Learning jQuery
This is the book that I used to teach myself jQuery.

jQuery Reference
This book is also published by Pakt Publishing. This is the book that I go to for reference.

jQuery in Action
Yes, the cover looks a little hokey, but some of the content in the appendixes is worth the book’s weight in gold.


  • Yehuda Katz


    Glad you’re finding the Appendixes useful – we put a lot of time in, so it’s nice to know it was worth it. Thanks for the shout out!