Categories
jQuery

Creating jQuery Plugins

Update: I was able to get permission to release the iScroll plugin! Check it out here.

Not too long ago I decided to write a jQuery plugin for making the use of iScroll a little less painful. Since I made the plugin at work I’m not really at liberty to share it. But what I can share is a step by step tutorial for creating a jQuery plugin of your own. Let’s get started.

Step 1: Scope

If you’ve been writing Javascript with jQuery for any amount of time, you find out pretty quickly that proper scoping is very important. You also learn that the $ symbol isn’t reliable. So what’s a coder to do? Make sure that your scope is contained within an anonymous function, and that you pass the jQuery object into that function.

(function($) {
	console.log($(document).jquery);
})(jQuery);

If you paste this code into your console (assuming jQuery is included), you should receive a print out of what version of jQuery you’re using.

Step 2: Functions

Now that you have the basic wrapper written, we need to write some real code. Before we start, there are 3 things you need to know.

  1. Functions are attached to the $.fn object.
  2. There may be more than one element passed into your function (plugin)
  3. We want to keep the chain alive if possible. (See jQuery Chaining if you have questions)

So, let’s write a function that adds the class “bob” to every item in the set. Yes, we could just use the .addClass() method, but then we wouldn’t need to write a plugin would we?

(function($) {
	$.fn.addBob = function() {  //Add the function
		return this.each(function() { //Loop over each element in the set and return them to keep the chain alive.
			var $this = $(this);
			$this.addClass("bob");
		});
	};
})(jQuery);

Step 3: Options

So let’s say you need to pass some options to your plugin. You know, like Bob’s last name, or if we should remove Bob. To accomplish this, all you do is create a defaultOptions object and load it with defaults. Then you use the $.extend function to overwrite it’s values with values passed in as a function parameter.

(function($) {
	$.fn.addBob = function(customOptions) {  //Add the function
		var options = $.extend({}, $.fn.addBob.defaultOptions, customOptions);
		return this.each(function() { //Loop over each element in the set and return them to keep the chain alive.
			var $this = $(this);
 
			//Determine what name to use.
			var name = "";
			if(options.lastName != "") {
				name = "bob-" + options.lastName;
			} else {
				name = "bob";
			}
 
			//Are we removing items?
			if(options.remove) {
				$this.removeClass(name);
			} else {
				$this.addClass(name);
			}
		});
	};
 
	$.fn.addBob.defaultOptions = {
		lastName : "",
		remove : false	
	};
})(jQuery);

Step 4: Running your plugin

Now that you’ve written your plugin, you need to run it!
Before

<ol id='x'>
	<li></li>
	<li></li>
</ol>
<ol id='y'>
	<li></li>
	<li></li>
</ol>

JS

	$("#x li, #y li").addBob({lastName: "awesome"});

After

<ol id='x'>
	<li class='bob-awesome'></li>
	<li class='bob-awesome'></li>
</ol>
<ol id='y'>
	<li class='bob-awesome'></li>
	<li class='bob-awesome'></li>
</ol>

JS

	$("#y li").addBob({lastName: "awesome", remove: true});

After

<ol id='x'>
	<li class='bob-awesome'></li>
	<li class='bob-awesome'></li>
</ol>
<ol id='y'>
	<li></li>
	<li></li>
</ol>

That’s all there is to it. If you have any questions, leave a comment and I’ll get back to you as soon as I can.

By Jack Slingerland

Founder of Kernl.us. Working and living in Raleigh, NC. I manage a team of software engineers and work in Python, Django, TypeScript, Node.js, React+Redux, Angular, and PHP. I enjoy hanging out with my wife and son, lifting weights, and advancing Kernl.us in my free time.

12 replies on “Creating jQuery Plugins”

“Since I made the plugin at work I’m not really at liberty to share it.” Perhaps worth asking if that is the case; not all code is really “top secret” and some code actually gains in value when you share it with the community.

While I agree in principal with open source software, it simply wasn’t possible to obtain permission from everyone that I need to get it from in time to post this. Perhaps in the future I will do so. Thanks for stopping by.

This is really wonderful, thank you. I would definitely be interested in seeing that iScroll plugin you wrote if you’re able to get that approval.

Phil

Very impressive! Thanks for sharing your knowledges. I have made some jQuery pluglin for me but I wasn’t very cautious with the scope, and also I must learn some of the JS properties.

Congratz for this article ^^

Hi Pomeh,

Honestly, it never occurred to me to mention the plugin authoring docs. My goal was to create a simple tutorial that was easy to follow, and I think I accomplished that. However, if people are looking for advanced resources or further information, that’s a great place to start!

Thanks for stopping by!

Comments are closed.