Creating Simple Hover Fade jQuery Plugin
In this tutorial we will look at very basics of jQuery Plugin creation, we will step by step create a plugin named hoverfade. This plugin will have just one task to accomplish, fade-in and fade-out the element when the mouse pointer enters and leaves its area. Plugin works pretty much like CSS hover effect and it also looks cool.
Loading the Library
Inside Plugin File “hoverfade.jquery.js”
If you open the plugin file and take a look inside, you’ll see that I have added “hoverfade” function to $.fn, it makes our plugin act like any other jQuery object method, we can now simply load our plugin file and call this function in the HTML page. But wait, plugin is not complete yet, we still need to program it to do the task we want.
In next line, $(this) represents a HTML element, Once we select the element with $ function, we will have all the jQuery methods we need, we can call methods like .click() .hide() etc.
In our case we want to set initial opacity of the element to 30%, so we just use .fadeTo() method to fade the element. Next I’ve created two functions OnEnter() and OnLeave(), which I’ve called these functions within mouseenter() and mouseleave() jQuery method.
Writing jQuery Plugin
You see, the whole code inside the plugin is very simple, and self explanatory. On page load, opacity of the elements is reduced to 30%, when user hovers the mouse on the element opacity is increased to 100%, and again on mouse leave opacity is reduced back to 30%.
Normally without the plugin, the jQuery code that fades the element looks like below, we simply take the idea and convert it to jQuery plugin.
Taking the example above, you can create more complex plugins for the jQuery. Always wrap your plugin code inside $.fn.XXXX like in syntax below, where XXXX should be your plugin name.
Applying the Plugin
You can now apply the plugin to the elements. jQuery code below will do exactly that:
The complete HTML file, with jQuery library and our plugin loaded. Noticed the plugin is applied to all the div element which has class “fader”, it contains images inside them, just hover over the element to see it in action. Similarly you can apply this plugin to other elements as well.
Saran Chamling. (He loves the web technology, and enjoys designing, exploring and writing about it @saaraan.com).