Either one knows what jQuery is, or one is just starting studying it, this article on how to write one's own jQuery plugin will be interesting for every Drupal developer. It’s very easy to do that, anyway. After you have read this article, you’ll be able to create your own plugins.
To write your own plugin, you will have to declare jQuery.fn object first, for example jQuery.fn.bestplugin where bestplugin will be the name of your plugin. That’s how it will look like:
jQuery.fn. bestplugin = function() { // your code will be here };
As you can see, though, jQuery stands instead of the usual $ sign. In order to use $, we'll have to prevent our plugin from conflicting with other JavaScript libraries, hence we'll name $ the following way:
(function( $ ){ $.fn.bestplugin = function() { // your code will be here }; })( jQuery );
For sake of illustrating I have chosen a plugin utilized in the case of ordinary image slideshow:
(function($) { $.fn.bestplugin = function(options) { var options = $.extend({ // Declaring settings by default that can be reset in plugin call timeOut: 2000, animateTime: 1000, opacity: 0.5 }, options); return $(this).each(function() { //return is used to continue a chain of calls of the given object var container = $(this), slides = $(this).children(), id, slidesLength = slides.length; container.css('position', 'relative'); slides.each(function() { $(this).hide().css({ 'opacity': options.opacity, 'position': 'absolute', 'left': 0, 'top': 0 }); }); var Show = function() { id = id || 0; var currentSlide = slides.eq(id); console.log(currentSlide); currentSlide.show().animate({ opacity: '1' }, options.animateTime, function() { setTimeout(function() { currentSlide.animate({ opacity: options.opacity }, options.animateTime, function() { currentSlide.hide(); id++; if (id == slidesLength) { id = 0 }; Show(); }); }, options.timeOut); }); } Show(); }); }; })(jQuery);