Convert your jQuery Code to a Plugin

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

efficiently organizing jQuery code

your code becomes easier to modify and follow

repetitive tasks are handled naturally

improves the speed with which you develop

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!).