Tutorials JavaScript Creating a jQuery Plugin

Creating a jQuery Plugin

Today's tutorial will be how to create your own jQuery plugin.

What can you do in a plugin?

Anything you can normally do with JavaScript.

Why create a plugin when I have custom functions?

You can put a plugin into a giant function, but it gets really messy. It's like classes in PHP, or good folder structure with your files on your computer; it's just more organized. Using methods, it's easier for you and your users to get the right functionality.

Create the plugin

First you have to create the plugin. The init method will be called when the plugin is initialized.

(function($) {    var methods = {    init : function(settings) {      return this.each(function(){                alert('Plugin initialization!');              }); // End object loop      } // End init  }; // End method        $.fn.myplugin = function(method) {        if ( methods[method] ) {      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));    } else if ( typeof method === 'object' || ! method ) {      return methods.init.apply( this, arguments );    } else {      $.error( 'Method ' +  method + ' does not exist on jQuery.myplugin' );    }          }; // End plugin  })(jQuery); 

Create more methods

After initializing the init method, you can create addition methods to call later.

play : function() {   return this.each(function() {    alert('play');  });}, // End playpause : function() {   return this.each(function() {    alert('pause');  });}, // End pauseupdate : function () {  return this.each(function() {    alert('update');  });} // End update

Allow options

If you use jQuery plugins, you will know that a lot of plugins allow you to have different options. You can set default options and allow your users to override them.

// Set default parametersvar defaultSettings = {  firstOption:  true,  secondOption: 1000,  thirdOption:  'Hello World!'}; // End options// Override default optionsvar settings = $.extend({}, defaultSettings, settings);// Get the optionsvar first  = settings.firstOption;var second = settings.secondOption;var third  = settings.thirdOption;

Calling your plugin

After loading jQuery and your plugin file, you can bind your plugin to elements.

$('.plugin').myplugin({  secondOption: 3000});

Do you have anything to start with?

Download a basic template for creating a plugin.

Have you ever made any plugins?

Check out Bare Bones Slider at http://www.bbslider.com. It's a basic slider that adds very little code so you have lots of customization.

That's it for this tutorial. Now go out and create something that will benefit users of the internet.

Posted by on . Category: JavaScript


Comments

No comments posted yet

You need to register or login to post new comments.