Here is a demo of what we will be creating.
If you want to skip the tutorial and download the files you can get them here
In this tutorial I am going to take my Simple Thumbnail Gallery script and turn it into my first Jquery Plugin. I will walk you through the process I used to create my first plugin and hopefully it will help you to start developing your own Jquery plugins.
Let’s start with HTML
The HTML for the script is very simple, just a few lists that contain the thumbnails and large images. You need to keep a few of the DIV Ids the same for the plugin to work. (#thumb_holder and #large_images)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple Photo Viewer</title>
<link rel="stylesheet" type="text/css" href="css/style.css" media="screen" />
<script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="js/jquery.vec_simple_gallery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready (function(){
$('body').simpleGallery();
})
</script>
</head>
<body>
<div id="wrapper">
<div id="content">
<div id="content_left">
<div class="info_holder">
<img src="img/title.jpg" alt="simple gallery" class="title"/>
<p class="by">Photos by: <span class="name">Chloe Rice</span></p>
<p class="by">Visit her at <a href="http://ohchloe.com" class="h_link">Oh Chloe dot com</a>
</p>
</div>
<ul id="thumb_holder">
<li><a href="javascript:void(0);"><img src="img/img1_thumb.jpg" alt="motherly" /> </a></li>
<li><a href="javascript:void(0);"><img src="img/img2_thumb.jpg" alt="xo" /> </a></li>
<li><a href="javascript:void(0);"><img src="img/img3_thumb.jpg" alt="keep your eyes open" /> </a></li>
<li><a href="javascript:void(0);"><img src="img/img4_thumb.jpg" alt="bacon bits" /> </a></li>
<li><a href="javascript:void(0);"><img src="img/img5_thumb.jpg" alt="nature sent packing" /> </a></li>
<li><a href="javascript:void(0);"><img src="img/img6_thumb.jpg" alt="snow man" /> </a></li>
</ul>
</div>
<div id="large_image_holder">
<ul id="large_images">
<li><img src="img/img1.jpg" alt="motherly" /></li>
<li><img src="img/img2.jpg" alt="xo" /></li>
<li><img src="img/img3.jpg" alt="keep your eyes open" /></li>
<li><img src="img/img4.jpg" alt="bacon bits" /></li>
<li><img src="img/img5.jpg" alt="nature sent packing" /></li>
<li><img src="img/img6.jpg" alt="snow man" /></li>
</ul>
</div>
</div>
</div>
</body>
</html>
If you did the simple thumb gallery tutorial you will see that not much has changed. The only difference is we have to initialize the plugin when the document is ready and we have to add our plugin script to the head.
<script src="js/jquery.vec_simple_gallery.js" type="text/javascript"></script>
Above is where my plugin code lives and must be included at the top of the document.
<script type="text/javascript">
$(document).ready (function(){
$('body').simpleGallery();
})
</script>
This is the line that initiates the plugin. What this script says is run simpleGallery on the body of the document. You can run simple gallery on any object in the DOM that you like. I used the body because this is an stand alone example. If you were to use it on your page you might just run it on the DIV that contains your gallery.
The Style
I am not going to go into detail about the CSS, it just contains the layout that I used for the example. As I wrote the plugin I decided to include the important CSS within the script, just to make it a little easier to use.
@charset "utf-8";
/****CSS RESET****/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {margin: 0;padding: 0;border: 0;outline: 0;font-size: 100%;vertical-align: baseline;background: transparent;}
body {line-height: 1;}
ol, ul {list-style: none;}
blockquote, q {quotes: none;}
blockquote:before, blockquote:after,
q:before, q:after {content: '';content: none;}
/* remember to define focus styles! */
:focus {outline: 0;}
/* remember to highlight inserts somehow! */
ins {text-decoration: none;}
del {text-decoration: line-through;}
/* tables still need 'cellspacing="0"' in the markup */
table {border-collapse: collapse;border-spacing: 0;}
/****Container CSS****/
#wrapper{width:1000px; margin: 0 auto;}
#content{width:1000px; float:left; display:inline; margin:30px 0 0 0;}
#content_left{width:300px; float:left; display:inline;}
/****gallery CSS*****/
#large_image_holder{width:650px; float:left; display:inline; margin: 0 0 0 18px;}
#large_images{width:650px; float:left; display:inline; padding:10px; border:#464646 3px dashed; height:400px;}
#large_images li{ left:10;}
#thumb_holder{width:300px;height:213px; float:left; display:inline; border:#464646 3px dashed;}
#thumb_holder li {width:80px; float:left; display:inline; margin:10px;}
.info_holder{width:300px;height:207px; float:left; display:inline;}
.title{float:left; display:inline; width:300px; }
.hide{display:none;}
/****Credist****/
.by{font-family:'Georgia',Times New Roman,Times,serif; text-transform:lowercase; color:#464646;font-style:italic; font-size:0.8em; line-height:1.1em; margin:0 0 0.5em 0; }
.name{font-family:'Georgia',Times New Roman,Times,serif; text-transform:lowercase;color:#E62E25;font-style:italic; }
.h_link{font-family:'Georgia',Times New Roman,Times,serif;color:#E62E25; font-style:italic;}
The Fun Part, The Jquery
Now that we have our page ready we can write our plugin code. The first step is to create an anonymous function so that our plugin does not interfere with anything else that might be going on in your pages.
(function($){
//This is where your plugin lives
})(jQuery);
Within this function we create and name the plugin script. We also want to be able to add options to our plugin to add flexibility to the things we create. In this case we store these options in the options parameter.
$.fn.simpleGallery= function(options){
}
Next we need to set up our default options so that if the user just wants to use the plugin straight out of the box it is ready to go without having to specify anything.
var defaults = {
timer: false,
interval: 5000
} settings = $.extend({}, defaults, options);
To demonstrate how options work I added a new function to the photogallery. I gave the user a slideshow option they can use if they choose to. This option is represented by timer in defaults and is set to false. I also gave them the ability to set the interval at which the slideshow would work at. After setting these defaults we save them to settings which contains the options for our plugin. To override the defaults all you have to do is add some code to your HTML like below.
<script type="text/javascript">
$(document).ready (function(){
$('body').simpleGallery({timer:true,interval:7000});
})
</script>
This sets the slideshow to true and gives it an interval of 7 seconds. This is just a basic example of what you can do with options. Some other ideas might be to give multiple transition types or allow the user to select the easing type as well. Options are very powerful and are what make Jquery plugins so great.
Now that the defaults are set up it is time to get to the meat of the plugin. First I am going to set up some variables to store things that I will use within the plugin itself. As we work through these variable will be pretty self explanatory.
var largImg = $('#large_images li');
var hold = $('#large_images')
var thumb = $('#thumb_holder li a');
var mainImg ='img0';
var current = 'img0';
var count= 0;
var len = largImg.size();
var timer
Next I want to add all the classes and styles that make this gallery work. The code below adds classes attributes and css properties that are needed for the plugin to work. I will go over each line below.
$(hold).css({'position':'relative','z-index':'1' });
$(largImg).each(function(index, element){$(element).attr("class", 'hide').attr("id", 'img'+index).css({'position':'absolute','z-index':'2' })});
$(thumb).each(function(index, element){$(element).attr("rel", 'img'+index);});
$('#img0').css('display', 'inline').addClass('current');
The first line sets the containers position to relative, so that we can stack the images on top of each other within the container by positioning them absolutely. Line two hides the large images, adds a unique id to each one and positions them absolutely on top of each other. Line three loops through the thumbs and adds a rel attribute that matches the id of the large image so we can make a connection between the two. Finally the last line shows the first image and adds a class of current to it.
Now we build the timer function.
function startTimer(){
if (count != len - 1){
$('.current').removeClass('current').fadeOut('slow').next('li').fadeIn('slow', function(){
$(this).addClass('current');
count=count+1;
});
}else{
$('.current').removeClass('current').fadeOut('slow')
$('#img0').fadeIn('slow').addClass('current');
count=0;
}
}
I am not gonna get into to much detail about the function itself, it basically moves through each image adding a class of current to the current image and removing it from the old one, as well as keeping track of where it is within the list so that when it gets to the end it will go back to the first image.
The important part of the timer is below where it is initialized because this is where the options are set
if(settings.timer == true && settings.interval>3000){
timer = setInterval( startTimer, settings.interval)
}else{timer = setInterval( startTimer, 3000)}
When building this I realized I needed to make sure the user did not try to set the interval to low. If they did the animations would not complete and it would turn into a mess, so I wanted to check some things before the timer is set. I used an if statement to do my checking, it says if settings.timer (which means we are reaching into settings and grabbing the value of timer) is equal to true and settings.interval (again reaching into settings and grabbing the interval) is greater than 3000 then start the timer. If they aren’t both true then set the interval to 3000. What this does is stops the user from screwing up the plugin by allowing the lowest interval to be 3 seconds.
Now we add our click function which makes all the magic happen.
$(thumb).click (function(e){
mainImg = $(this).attr('rel');
if(mainImg != current ){
clearInterval(timer)
$('.current').removeClass('current').fadeOut('slow');
$('#'+mainImg).fadeIn('slow', function(){
$(this).addClass('current');
current = mainImg;
});
}
});
This function checks to make sure the image you clicked on is not the current, if it isn’t it stops the timer (because we don’t want it running after we click) and then fades the old image out and the new one in.
There is only one last thing left to do and that is to add this code at the bottom so that the plugin can be extended. Always add this snippet to the end of your plugin code.
return this;
Below is the full script all put together.
/* http://jamesvec.com
simple thumbs v1.1 Plugin Version
Written by james vecchio (jamesvec[at]gmail.com) June 2010.
Feel free to use this on any project.
I would love to see what people do with it, so drop me a line
if you use it.
*/
(function($){
$.fn.simpleGallery= function(options){
var defaults = {
timer: false,
interval: 5000
}
settings = $.extend({}, defaults, options);
var largImg = $('#large_images li');
var hold = $('#large_images')
var thumb = $('#thumb_holder li a');
var mainImg ='img0';
var current = 'img0';
var count= 0;
var len = largImg.size();
var timer
$(hold).css({'position':'relative','z-index':'1' });
$(largImg).each(function(index, element){$(element).attr("class", 'hide').attr("id", 'img'+index).css({'position':'absolute','z-index':'2' })});
$(thumb).each(function(index, element){$(element).attr("rel", 'img'+index);});
$('#img0').css('display', 'inline').addClass('current');
function startTimer(){
if (count != len - 1){
$('.current').removeClass('current').fadeOut('slow').next('li').fadeIn('slow', function(){
$(this).addClass('current');
count=count+1;
});
}else{
$('.current').removeClass('current').fadeOut('slow')
$('#img0').fadeIn('slow').addClass('current');
count=0;
}
}
if(settings.timer == true && settings.interval>3000){
timer = setInterval( startTimer, settings.interval)
}else{timer = setInterval( startTimer, 3000)}
$(thumb).click (function(e){
mainImg = $(this).attr('rel');
if(mainImg != current ){
clearInterval(timer)
$('.current').removeClass('current').fadeOut('slow');
$('#'+mainImg).fadeIn('slow', function(){
$(this).addClass('current');
current = mainImg;
});
}
});
return this;
}
})(jQuery);
I hope that this tutorial helped you to understand how to create a Jquery plugin on your own. This tutorial is loosely based off of a great screencast on Nettuts that you can view here
You can download all the source files here

Pixel2life
August 30, 2010 at 9:29 am
Thank you so much for submitting your tutorial to Pixel2life, your submission has been accepted
I look forward to more tutorials from your site in the future!
[Reply]