I have been spending a bit of time lately figuring out how to create my own plugins for jQuery. It doesn’t take much to accomplish and I thought it would be a good idea to put together a small tutorial to show everyone just how easy it can be. For this example, I will create a plugin to increase the font size of a selected div when a link is clicked.
To start, we are going to create a wrapper function which will allow us to use $ without conflicting with other JavaScript libraries:
(function($) {
// our plugin goes here
})(jQuery);
Next we need to let jQuery know we are creating a new plugin by using $.fn. Let’s call our function increaseFontsize and give it a few variable, such as size, speed, easing and callback, so it works just like other jQuery functions.
(function($) {
$.fn.increaseFontsize = function(size, speed, easing, callback) {
// the guts of our plugin goes here
};
})(jQuery);
Once you have done that, you can create the code that will make our plugin do what we want it to, which is increase the font size of a selected div.
The final plugin code looks like this:
(function($) {
$.fn.increaseFontsize = function(size, speed, easing, callback) {
return this.animate({fontSize: size}, speed, easing, callback);
};
})(jQuery);
Now we can use our plugin just like any other jQuery function.
jQuery(function() {
jQuery('a.increase').click(function() {
jQuery('div.paragraph').increaseFontsize(16, 'fast');
});
});
Try it out below to see it work.
Increase Font Size | Decrease Font Size


