Tutorial: Creating a jQuery plugin
Learn how to create a jQuery plugin from scratch – the basics, options, compatibility and examples.
A plugin is written as a method or function.
Creating a jQuery Function
The function has to return
this.each(..) to maintain chainability – so that the function can be used with a single or several jQuery objects.
Creating a jQuery Method
Make your plugin as flexible and user friendly as possible using options. The
$.extend() method takes two or more objects as arguments and merges the contens of them into the first object.
A function that set text color (red by default).
We can now choose use this function passing the settings parameter or not.
$ variable might be used by other plugins, use a alias technique to make your plugin forward-compatible.
jQuery to the function and can now use whatever alias for jQuery we like. So instead of
The jQuery Plugin Checklist
This is a list of important points to remember when developing a jQuery plugin (from jQuery.com).
- Name your file jquery.[insert name of plugin].js, eg. jquery.debug.js
- All new methods are attached to the jQuery.fn object, all functions to the jQuery object.
- inside methods,
thisis a reference to the current jQuery object.
- Any methods or functions you attach must have a semicolon (;) at the end – otherwise the code will break when compressed.
- Your method must return the jQuery object, unless explicity noted otherwise.
this.eachto iterate over the current set of matched elements.
- Always attach the plugin to jQuery instead of
$, so users can use a custom alias via
jQuery Plugin Templates
These are two good code templates to start from when developing a jQuery plugin.
Example: jQuery Slideshow Plugin
I have chosen to use very simple examples so far in order for you to get started. The following example is a bit more complex and might help to get your inspiration going.
It uses the function
setInterval() in combination with the jQuery effects
fadeIn() to cycle any number of images within a HTML-element.
To enable slideshow on the
Because we allow settings to change the behaviour of the slideshow, we could make it wait 5 seconds between images and set the “fade” duration to 200 ms using:
It’s not harder than that! Good luck in creating your own jQuery plugins!