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 :)