Join Joe Chellman for an in-depth discussion in this video Converting a filter into a plugin in one easy step, part of jQuery: Creating Plugins.
- View Offline
- In this video, we're going to take our code and make it into a real plugin. It doesn't take very long, so let's see how we do that. I'm going to do this inside the same script tag in the same file. Plugins are usually distributed as standalone files, but it will still work this way. So, just to make everything easy to see in the same file, I'm gonna keep everything right here. First, I'm going to add a little bit of white space where the plugin will go and then I'm going to create an immediately invoked function expression. If you've never seen this before, you can look it up in your favorite search engine.
This will be the plugin. So, I'm going to call this equalizeheight. You may recall down here, when I figured out how I'd want this to be called later, that was what I called it. So, this is going to be a new anonymous function. Like this. So, in writing this line, I've now created a plugin. It doesn't do anything. There's nothing inside it, but this, itself, is technically the plugin. Now, it needs to do stuff. So, I'm just going to copy my code from down here. I'll actually cut it using command + X or Ctrl + X on Windows and I'll paste it in using Command + V on the Mac or Ctrl + V on Windows.
I know that in my code, it will always refer to jQuery. Okay, so now I can save this code and try it out. Like I said, this is a plugin now, so I should be able to invoke it, using a line like this. Let's try it. I'll switch over to my browser and load or reload this file as needed and I can see that nothing has changed up here on stories one. However, if I scroll down to stories two, I can see that these all work. It's probably not too hard to see what's going on here, but let's switch back to the code and look.
OK, very clearly, the problem is, that I'm still using stories two right there in my plugin. So, no matter what I do here, it's always going to refer to stories two. That's not good and we're going to have to fix that. But, for now, we've actually created a plugin. There it is and we can call it just like any other jQuery method, like this. So, that's how you do the initial work of writing a jQuery plugin and next up, we'll look at how to extend it and make it work correctly.
- Writing basic jQuery filters
- Converting filters to plugins
- Converting code to plugins
- Making plugins configurable
- Adding appearance options and functions
- Distributing jQuery plugins