In this tutorial we will look at very basic of creating a jQuery Plugin, and we will step by step learn to create a plugin named hoverfade. This plugin will do just one task, fade-in and fade-out when the mouse pointer enters and leaves the elements, useful if you want to replace standard css link hover effect, and the best thing about the jQuery plugin is; it can be applied to any element we want.
Loading the Library
Inside Plugin File “hoverfade.jquery.js”
This is jQuery code inside “hoverfade.jquery.js” file. A very simple plugin file just enough to fade in and fade out any HTML element, when the mouse pointer enters and leaves.
Writing jQuery Plugin
As you can see code inside our plugin file is very simple and already clear to the point. On load all the elements opacity is reduced to 30%, and when user hovers the mouse on the element, opacity is increased to 100% and on mouse leave opacity is reduced back to 30%.
Before you write a plugin file, you must know how your code works in a page with jQuery loaded. It’s always a good idea to start writing your code in same page something like code below, see how your code works and then implement it in a plugin :
You can easily create more complex plugins using jQuery methods. One thing to remember when coding jQuery plugin is to wrap your codes in :
Where XXXX should be your plugin name.
Applying the Plugin
Only thing now left to do is to apply our plugin to the elements. jQuery code below will do exactly that
The complete HTML file, with jQuery library and our plugin loaded. As you may have noticed the plugin is applied to all the div element with class “fader”, which contains images inside them. You can apply this plugin to other elements as well.