Create better jQuery plugins
jQuery, used by the major companies and the top websites, is pretty much the standard in the I want to make things cool and easy
.
Most of the time we create simple script that do whatever we need, but we have to think about the big picture. In this case, we have to create more robust script that will last longer ... such as jQuery Plugins.
Now, when you create jQuery you have to think on what and how you can do it! Here's some tips you have to learn and remember everything you create your plugins.
Always return a value
If your script does not return a specific value, you can either return true or false or return the current object.
// JS code return true; }
or returning the object
// JS code return this; }
On the first example, you make sure nothing after the return is executed and stop your script and on the second example you can do something like this:
$("#item").plugin().fadeIn();
Use clean and simple code
By using clean and simple code, you will make your plugin very easy to maintain and very easy to update. If your plugin requires a lot of parameters or function calls, you might have a problem here. Try to take advantage of the DOM, the HTML5 tags and the class or ID attributes without overloading your code. Example:
<article id="uniqueName"> <div>My content</div> </article>
Then simply call your plugin like this:
$("article#uniqueName").myPlugin();
Use unique non-reserved name
jQuery has a big plugin library. Before naming your plugin, make sure it is not already taken and also don't use reserved words like: css or fadeIn.
HTML5 data attributes
HTML5 brings a new set of attributes: the data type. This can be very powerful and take advantage of it. Example:
<article id="uniqueName" data-id="1" data-label="Label"> // some code </section>
These data attributes can be accessed using the .data
method. Example:
$('#id').data("id").
Document, document, and document
When writing a plugin, make sure you write documentation. Not all the users of your plugin is an experimented developer. Here's some tips to write your documentations:
- What exactly your plugin do
- Easy to understand
- If you have parameters, give details explanations
- Plenty of examples
- Write for inexperienced users
- Make an Offline documentation
Test, test, and test again
Remember to test your plugin over and over, using a different Internet Browser each time.