Creating a jQuery plugin

3 May, 2011

In this tutorial, we’ll show you the basics of how to create your very own jQuery plugin by showing you how to create a jQuery accordion. This tutorial assumes you already have a working knowledge of html, css and some jQuery.

This has many advantages, it makes reusing your code much easier and saves you time when coming to different projects! Also, it can help if you work as part of a team, it’s much easier to point a team member to a file and tell them to just perform a simple jQuery function call in the head of your html rather then having to copy over 100 lines of code that they didn’t write and don’t understand.

Setting up

First we’ll create a basic html page that will include the jQuery library from Googles servers, our accordion script file and a css file for styling. We’ll also setup the page with a basic html list with sub menus.

Here’s the html code we’ll be working with.

HTML


<ul>
  <li>
    <a href="#">Premier League</a>
    <div>
      <ul>
        <li><a href="#">Arsenal</a></li>
        <li><a href="#">Chelsea</a></li>
        <li><a href="#">Man United</a></li>
        <li><a href="#">Man City</a></li>
        <li><a href="#">Spurs</a></li>
        <li><a href="#">Liverpool</a></li>
      </ul>
    </div>
  </li>
  ...
</ul>

and here’s the css code we’ll be working with which I’ve put into a file called ‘style.css’ and placed this in the same directory as the html file.

CSS

[css]
.accordion {
list-style:none;
margin:0;
padding:0;
background:#2E90BF;
}
.accordion ul {
list-style:none;
margin:0;
padding:5px 0 0;
background:#f8f7f3;
}
.accordion li {
background:#2E90BF;
float:left;
width:100%;
margin-bottom:4px;
}
.accordion li a {
display:block;
font-weight:bold;
color:#fff;
padding:10px 10px 9px;
}
.accordion li .content { display: none; }
.accordion li li {
background:#82D4FA ;
border-bottom:1px solid #2E90BF;
margin:0;
float:none;
width:auto;
color: #fff;
}
.accordion li li a {
color:#000;
font-weight:normal;
height: 15px;
line-height: 15px;
margin-left: 10px;
}
.accordion li li.active, .accordion li li:hover {
background:#F87A01;
}
.accordion li li.active a, .accordion li li:hover a {
color:#fff;
}
[/css]

Writing the plugin

To start with, I created a folder called ‘js’ and created a file within this folder called ‘jquery.accordion.js’, this is the file which will house our plugin.

To kick start this plugin we use the following code, the highlighted word is the function name which will be used to call the plugin.

jQuery

[javascript]
(function($){
$.fn.accordion = function(options) {
// plugin code will go here
};
});
[/javascript]

That is the basis for the plugin, if you notice we have set function(options), this will allow us to specify some options for the plugin. For this plugin the options I’ll be allow are amending the class names for the clickable link, the div containing the sub menu and the class to apply when a tab is open (or active).

We use the following code to setup options, this works by first specifying some defaults and then using jQuerys extend function to merge any passed options into the default array.

jQuery

[javascript]
// set some defaults
var defaults = {
aBtn: ‘btn’,
aContent: ‘content’,
active: ‘open’
};
// merge
var options = $.extend({}, defaults, options);
[/javascript]

This next piece of code will run on load, this sets up the list ready for being made into an accordion by hiding all the content (if not already hidden) and opening any tabs that need to be open as default. Notice how we reference the options variable from the above section of code, this allows the plugin to run off either the default values or the passed parameters.

jQuery

[javascript]
// check for clicks
$('.' + options.aBtn).click(function() {
// object for the button that has been clicked
var obj = $(this);

// check see if we have click the currently active tab
// as we won’t be able to check after closing the tabs!
var slide = true;
if(obj.hasClass('open'))
{
slide = false;
}

// close all the current elements
$('.' + options.aContent).slideUp().removeClass(options.active);
$('.' + options.aBtn).removeClass(options.active);

// check if we should still slide
if(slide)
{
// make the clicked button active and oepn
obj.addClass(options.active);
obj.siblings('.' + options.aContent).addClass(options.active).slideDown();
}

return false;
});
[/javascript]

Once the last piece of code is in place that should be it. If you go back to the html briefly, you should notice the call to "$('.accordion').accordion();". This, like all other jQuery plugins is the bit that kick starts the plugin. It’s here that you could pass in the options as dicussed earlier in the tutorial. You could for example start the plugin with something like this.

jQuery

[javascript]
$('.accordion').accordion({
'aBtn' : 'accordion_button',
'aContent' : 'accordion_content',
'active' : 'accordion_active'
});
[/javascript]

This would mean changing all references to 'btn' to 'accordion_button', 'content' to 'accordion_content' and 'open' to 'accordion_active'.

View post demoDownload post source

Conclusion

This tutorial was obviously only a simple example of how to create a jQuery plugin but hopefully should be a platform for you to build on to create your own bigger plugins. One final recommendation is to look at other plugins, it goes without saying that there is so much that can be learnt from looking how other people have done things and experimenting then with the code!

3 Comments

Steve
16th October 2017 at 9:16am

Thank you! Your instructions are easy to follow, and I had great results in a matter of minutes. I appreciate you sharing your expertise. Cheers!

Post reply
Bindu
16th October 2017 at 9:16am

Thanks Mike. this article helped me a lot. I think it this went unnoticed: when we run the demo, by default (i mean on page load), one of the menu is expanded!!! i am quite new to jquery and have been struggling to fix this.
to my understand,
$(document).ready(function () {
// hide all the content panels
$('.' + options.aContent).hide();
this piece of code is responsible for hiding all the menus initially.
Can you please help me out?
Thanks in advance....

Post reply
Bindu
16th October 2017 at 9:16am

Hey i could fix it :-) it was very simple, there is class="btn open". if we remove "open", this is fixed. :-)

Post reply

Leave a comment

Replying to: - Cancel