jQuery plugins are just functions attached to the jQuery object
There are 2 types of plugins that you can make
- Plain functions, like the jQuery.each
- functions that work with a jQuery selection, like jQuery().each
How to make a jQuery function plugin
(function($){
$.highest = function(){
return Array().slice.call( arguments ).sort(function(a,b){
return b - a;
});
};
})(jQuery);
Usage
jQuery.highest(1, 1, 2, 3);
How to make a jQuery selection plugin
(function($){
$.fn.reverse = [].reverse;
})(jQuery);
Put it in a javascript file
You can run it like this:
jQuery('dt').reverse().each(function(i, el){
console.log(el);
});
It will reverse the jQuery selection/stack, now you can run each backwards
How to run jQuery plugins
This is for plugins that need to change the document as soon as they are run
On ready (as soon as the document loads, before images)
jQuery(function($, undefined){
$('.green').greenify();
});
On load (as soon as the document and all the images load)
jQuery(document).load(function($, undefined){
$('.green').greenify();
});
How to make delegated jQuery plugins
(For dynamically changing HTML)
(function($){
$.greeinfyOnClick = function(selector){
$(document).on('click', selector, function(){
$(this).css('color','green');
});
};
})(jQuery);
How to run delegated jQuery plugins
You can run these in the >head< of the document before the document is even ready
(function($){
$.greeinfyOnClick('a');
})(jQuery);
The advantage of delegated plugins is that they will work even if you replace all the elements in the document
The other advantage is that this will work immediately, even before the document is loaded (perfect for plugins that need to be responsive, like lightboxes)
All event based plugins should use this method
0 comments:
Post a Comment