Convert your jQuery Code to a Plugin

By Sam Deering


It’s pretty easy to turn your code straight into jQuery plugin ready for use with any website. The hardest part is finding a way to properly structure your code so it is independent and easy to use.

Advantage of converting jQuery code into a plugin

  1. efficiently organizing jQuery code
  2. your code becomes easier to modify and follow
  3. repetitive tasks are handled naturally
  4. improves the speed with which you develop
  5. plugins are organised and promotes code reuse

Creating jQuery Plugin Tips

Leave specifics out of the code (ie anything that relates directly to the example that the jQuery code is being used for).
Rewtite code to include the “this” object instead of hard-coding a selector to make it more generic
Make the JavaScript and CSS code of the plugin to separate files

jQuery Plugin Structure

//You need an anonymous function to wrap around your function to avoid conflict  (function($){        //Attach this new method to jQuery      $.fn.extend({            //This is where you write your plugin's name          pluginname: function() {                //Iterate over the current set of matched elements              return this.each(function() {                    //code to be inserted here                });          }      });    //pass jQuery to the function,  //So that we will able to use any valid Javascript variable name  //to replace "$" SIGN. But, we'll stick to $ (I like dollar sign: ) )  })(jQuery);  

How to convert jQuery Code to a plugin

All you need to do is extend the $.fn object with your own function (Let’s not reinvent the wheel, see the example below!).

Examples of Simple jQuery Plugins and Tutorials

  1. Simple Plugin Tutorial to Animate a Menu
  2. Plugins/Authoring Official Documentation
  3. jQuery Plugin Tutorial, In-Depth For Absolute Beginners
  4. How to Build a Simple Content Slider jQuery Plugin
  5. The Definitive Guide to Creating a Practical jQuery Plugin
  6. How To Create A Plugin For jQuery
  7. Learn How to Create a jQuery Plugin
  8. A Plugin Development Pattern

No Reader comments



Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.