How to create a jQuery plugin

I tend to write everything i do in JavaScript as a jQuery plugin. Even if it's mostly useless, i think it's a convenient way to encapsulate the code. In this post I'll show how to make a simple plugin that replaces the background color of an element when the mouse hovers over it. In real life you would probably want to do this with CSS pseudo-classes.

Step 1 - Get ready

All plugins i write always starts with the same template:
(function($){
   $.fn.backgroundHover = function(options) {
      return this.each(function () {
         // Code goes here
      });
   };
})(jQuery);
Line 1 and 7 are only there to protect from $-function overloading by using variable scoping. On line 2 the plugin function is defined in the prototype of jQuery. fn is just an alias for prototype. Since a plugin can be applied to many DOM nodes in one call, we must loop through every element on line 3.

Step 2 - Get Set

Now we just need to write the actual code for the plugin. First we gonna add a couple of lines in the beginning of the plugin function to provide default values for the options.
$.fn.backgroundHover = function(options) {  
      options = $.extend({
         background: 'red',
      }, options); 
Then we add some code inside the each-function:
var self = $(this);
   self.mouseover(function() {
      self.oldBG = self.css('backgroundColor');
      self.css('backgroundColor',options.background);
   });

   self.mouseout(function() {
      self.css('backgroundColor',self.oldBG);
   });   
Line 1 is just a convenience variable that I usually define to get rid of unnecessary $-calls. Line 2-5 binds a function to the mouseover event. When the mouse is above the element the old background color is stored for later use and the new one is set. Line 7-9 restores the original background color of the element when a mouseout event is triggered.

Step 3 - Go!

That's it, the plugin is finished! And all that's left is to use it:
jQuery("#special").backgroundHover( { background: '#306090' } );
The complete source is as follows:
(function($){
   $.fn.backgroundHover = function(options) {
      options = $.extend({
         background: 'red',
      }, options); 

      return this.each(function () {
         var self = $(this);
         self.mouseover(function() {
            self.oldBG = self.css('backgroundColor');
            self.css('backgroundColor',options.background);
         });
   
         self.mouseout(function() {
            self.css('backgroundColor',self.oldBG);
         });   
      });
   };
})(jQuery);

Epilogue

If you found this post useful or have suggestions on how i can improve it, please leave a comment. Negative comments without any constructive criticism will be deleted without hesitation. My blog, my rules :)

Comments

NParsons said…
Hey, nice, easy-to-follow outline there! Personally, I would use the jQuery hover() function rather than separate mouseover and mouseout, since that is a bit more efficient, but great article! Thanks!
Erik said…
You're right, it's probably more efficient. I chose to do it this way because i thought the source would be a bit easier to read :) Thanks for the comment.
Anonymous said…
Great job, thanks
123 said…
http://remind.com.br/projetos/criar-blog-gratis/replicahandbags69/
http://remind.com.br/projetos/criar-blog-gratis/ureplicawatches/
http://remind.com.br/projetos/criar-blog-gratis/ureplicawatches1987/
http://replbags.livejournal.com/
http://replcawatche.livejournal.com/
http://repldbags.livejournal.com/
http://replica69bags.insanejournal.com/
http://replicabag242.livejournal.com/
http://replicacheap.21classes.com/weblogCategory/1951uut1lrg4t
http://replicacheap.ayubd.com/

Popular posts from this blog

Cubing for charity #4

jQuery floating table header plugin

Seascape - OpenVR adaptation of a 4k intro