I’ve been writing a ton of jQuery plugins lately and decided to create myself a nice little boilerplate with some common structures. This boilerplate will provide the necessary Object Oriented Class based setup for a plugin and its extension of the jQuery.fn Object.
Features of this Boilerplate:
- Fully chainable plugin use
- Object Oriented JavaScript structure
- jQuery UI style syntax for running commands, reading properties
- Automatic read of HTML5 data properties for default option overrides
Instantiate the plugin:
Initiate the plugin just like any other jQuery plugin and pass an option object to override default options.
1 2 3 4 5 6 7 8 9 |
// Standard initiation with default options $('.my-element').myPlugin(); // Or initiate with custom option overrides $('.my-element').myPlugin({ myOption: false }); |
Run plugin methods:
Easily run plugin methods by passing the method name to the plugin function.
1 2 3 |
$('.my-element').myPlugin("myMethod"); |
Read options:
Read option values for a plugin instantiation with the option method. Pass the option value to read as the second argument.
1 2 3 |
$('.my-element').myPlugin("option", "optionName"); |
Override default options with HTML5 data properties:
Easily deploy your plugin without having to write much custom JavaScript for elements that will have specific options settings by specifying the option as an HTML5 data property.
HTML:
1 2 3 |
<div class="my-element" data-myOption="foobar"></div> |
JavaScript:
1 2 3 4 5 6 7 |
// Initialize the plugin $('.my-element').myPlugin(); // Read the HTML5 overriden option $('.my-element').myPlugin('option', 'myOption'); // "foobar" |
This plugin boilerplate is available free of use under the GPLv3 or compatible license.
Hey Dave,
This looks awesome, and I’m really hoping I can use it for some of my projects eventually. Do you have any examples of projects that you’ve used this on? It would be very cool/helpful to see it in action.