Your First Plugin
A rough start...
First, let's remember what we need plugins for. My answer — for creating reusable code with a convenient interface. Let's write some, starting with a simple task:
— On clicking a paragraph, the text should turn red
JavaScript, Not Even jQuery
So we don't forget our roots, let's start with a native JavaScript implementation:
// wrap everything in a function
let loader = function () {
// find all paragraphs
let paragraphs = document.getElementsByTagName('P');
// iterate and attach a handler
for (let i = 0; i < paragraphs.length; i++) {
// the handler itself
paragraphs[i].onclick = function() {
this.style.color = "#FF0000";
}
}
}
// naturally, all the code should run after the page is fully loaded
document.addEventListener("DOMContentLoaded", loader);This code isn't universal and was written just to emphasize the convenience of using jQuery one more time ;)
jQuery, But Not a Plugin Yet
Now we can simplify this code — plug in jQuery and get the following version:
An Actual jQuery Plugin
We've accomplished the task, but where's the code reuse? Or what if we need green instead of red? This is where things get interesting. To write a simple plugin, you just need to extend the $.fn object:
If we want to do it properly, we need to scope the $ variable to our plugin only, and also return this so we can use chaining. Here's how:
Let's add a color option and get a working plugin:
Usage:
As a result, every click will change the paragraph color to red. Since we're using a global variable to store settings, the second plugin call will change the value for all elements:
We can make a small change and separate the settings for each call:
The difference is just one "var". I can't even imagine how many hours have been killed searching for a missing "var" in JavaScript. Be careful:
Working with Object Collections
This is straightforward — just remember that this contains a jQuery object with a collection of all elements, i.e.:
If we want to process each element, we build the following construct inside our plugin:
Public Methods
Alright, we've written a "cool" plugin, and now we need to add more functionality — let the color be controlled by several buttons on the site. For this, we'll need a color method that will be in charge of everything. Here's the code for the finished plugin — let's study it together (pay attention to the comments):
And here's a small example of using these methods:
To understand this piece of code, you just need to wrap your head around the arguments variable and the apply() method. Here are some articles dedicated to them, go for it:
About Event Handlers
If your plugin attaches any handler, it's best (read — always) to attach that handler in its own namespace:
This trick lets you remove all your handlers at any time or trigger only yours, which is super convenient:
— Deja vu? Ok!
That's all about regular plugins. Thanks for your attention, everyone.
Last updated