Labels: jQuery Plugin
jQuery has a .data() method for storing data in the DOM should you need to for one reason or other. This is preferable to storing data in some other attribute such as "rel" or "alt" which is often seen in tutorials and examples on blogs.
For example if you had a elements with the id "foo" and "bar" you could set data with a name of "fruit" to "orange" for #foo and "banana" for #bar like so:
$('#foo').data('fruit', 'apple'); $('#bar').data('fruit', 'banana');
To fetch the value at a later time call the .data() method just passing in the name like so, where the value is displayed in an alert dialog:
alert( $('#foo').data('fruit') );
If you don't want to assign the data to a particular element you could always assign it to the body instead:
$('body').data('fruit', 'orange'); alert( $('body').data('fruit') );
Labels: jQuery
The Basics
A plugin is written as a method or function.
Creating a jQuery Function
Syntax
The function has to return this.each(..) to maintain chainability – so that the function can be used with a single or several jQuery objects.
Example
Creating a jQuery Method
Syntax
Example
Options
Make your plugin as flexible and user friendly as possible using options. The $.extend() method takes two or more objects as arguments and merges the contens of them into the first object.
Example
A function that set text color (red by default).
We can now choose use this function passing the settings parameter or not.
Compatibility
As the $ variable might be used by other plugins, use a alias technique to make your plugin forward-compatible.
We pass jQuery to the function and can now use whatever alias for jQuery we like. So instead of $ you could also use any other valid JavaScript variable name.
The jQuery Plugin Checklist
This is a list of important points to remember when developing a jQuery plugin (from jQuery.com).
- Name your file jquery.[insert name of plugin].js, eg. jquery.debug.js
- All new methods are attached to the jQuery.fn object, all functions to the jQuery object.
- inside methods, this is a reference to the current jQuery object.
- Any methods or functions you attach must have a semicolon (;) at the end – otherwise the code will break when compressed.
- Your method must return the jQuery object, unless explicity noted otherwise.
- Use this.each to iterate over the current set of matched elements.
- Always attach the plugin to jQuery instead of $, so users can use a custom alias via noConflict().
jQuery Plugin Templates
These are two good code templates to start from when developing a jQuery plugin.
Function Template
Method Template
Example: jQuery Slideshow Plugin
I have chosen to use very simple examples so far in order for you to get started. The following example is a bit more complex and might help to get your inspiration going.
It uses the function setInterval() in combination with the jQuery effects fadeOut() andfadeIn() to cycle any number of images within a HTML-element.
The Setup
HTML
CSS
JavaScript
Usage
To enable slideshow on the #slideshow div, we simply call it using the following JavaScript code:
Because we allow settings to change the behaviour of the slideshow, we could make it wait 5 seconds between images and set the “fade” duration to 200 ms using:
Example 2:
jQuery.fn.secondPlugin = function (number1, number2, options) { myoptions = jQuery.extend ({ operation: "sum", label: "The result is" }, options); $(this).html (myoptions.label + " (" + myoptions.operation + ")" + myoptions.number1+myoptions.number2); } |
In the above code, check out the way we provide default settings in case the two strings are not passed to the plugin function. This way we can call either
$('#test').secondPlugin (1, 2); |
to get
<span id="test The result is (sum) 3</span> |
or
$('#test').secondPlugin (1, 2, { operation: "sums two numbers together", label: "We got" }); |
if you prefer
<span id="test We got (sums two numbers together) 3</span> |
Until now, we've messed with the jQuery.fn object, which is responsible for elements interaction, and we never mentioned the jQuery object itself, which handles internal processing. By extending it, we are thus allowed to create our own functions and even selectors for others to use! Here's how new methods can be added:
jQuery.fn.extend ({ myFirstFunction : function () { alert ("first function") }, thisIsTheSecond : function (message) { alert ("2nd: "+ message) } }); |
and then called without any problems
$.myFirstFunction (); $.thisIsTheSecond ("hello"); |
In a very similar fashion you can create your own selectors, provided they don't exist yet.
jQuery.expr[":"].startsWith = function (element, index, tokens) { if (!tokens[3]) return false; return eval ("/^[/s]*" + tokens[3] + "/i").test ($(element).text()); }; |
As you can see, the function takes three arguments, being: 1) the matched element, 2) the index of the element and 3) an object that contains parse tokens; the first element of the array is the full filter string (including parameters), the second one is the ":", the third one is the filter name and, finally, the fourth is the parameter.
You should always check whether the parameter has been passed or not, since the filter could stop working in the latter case.
Example 4:
01 | $.fn.makeDiv = function(options) {//set up the function and give it a name |
02 | settings = $.extend({//set the default values for the options |
03 | color : 'white', |
04 | background : 'blue', |
05 | width : 400, |
06 | height : 100, |
07 | }, options); |
08 | $(this).css({//set the css properties of the selected element |
09 | color : settings.color, |
10 | background: settings.background, |
11 | width : settings.width, |
12 | height : settings.height |
13 | }); |
14 | }; |
<script> |
2 | $(document).ready(function(){ |
3 | $('div').makeDiv(); |
4 | }); |
5 | </script> |
01 | <script> |
02 | $(document).ready(function(){ |
03 | $('div').click(function(){ |
04 | $('div').makeDiv({ |
05 | background: 'green', |
06 | color: 'black', |
07 | height: 200, |
08 | width: 50 |
09 | }); |
10 | }); |
11 | }); |
12 | </script> |
test:
Labels: jQuery Plugin