jQuery Cross Fade

for a quick 5 page website basically what we wanted to create was a hover effect when a person hovers over a link. So we could use a couple of methods, but I thought that it would be a good excuse to create a plugin. The reason for a plugin is because on each link a different image will fade into view, and after you mouse off the link, it will fade away. So I could write this fade function many times, however, that is a lot of code to manage, and it would make more since to write it once. To begin with I had a few absolutely placed Div’s on the page which each div holds 1 background image that we will show and hide. I next hid each div by setting the opacity to 0.

The CSS:

.about { position: absolute; top: 0; left: 100px; width: 900px; height: 350px; background: #FFFFFF url(images/1.jpg) no-repeat; }

The first part of the JS:

var backGrounds = $('.vendors, .cinematography, .production, .talent, .about '); backGrounds.css({"opacity":"0.0"});

Now we have a div with each image, and all of those div’s are hidden using opacity.

The Plugin

Next I created a cross fade, in which each link when hovered, will fade in a div tag. The HTML:

<ul class="menu"> <li id="ctl00_genAbout"> <a href="about.aspx">About</a> </li> ....

Here is a unordered list used to build a menu.

The JS element call:

$("#ctl00_genAbout").crossFade(".about");

Here I have create a plugin called “crossFade”.

The plugin: (function( $ ){ $.fn.crossFade = function( option ) { this.hover(function(){ $(option) .fadeTo("slow", 1.0); }, function(){ $(option).fadeTo("slow", 0.0); }); }; })( jQuery );

From the call is in the menu an item with the id ctl00_genAbout - is hovered the div .about is fades in and then when it fades out when a mouse moves off the link. In the plugin it uses the jQuery the keyword “this” refers to to the id “ctl00_genAbout” - the second paramater “.about” is the option marker in the function.

crossFade example

Conclusion

Overall it is very easy to build a jQuery plugin. Overall in less than an hour I figured out how to build the plugin, and even though this is a very simple example, it is still useful in a real world example. For more information on how to build or author a plugin see this page.