CSS Code, DHTML Code, JavaScript Code

DHTML: Fade an Object or image in and Out

This function is great to dynamically fade images in and out. You could use JavaScript to dynamically change an object's display to 'block' or 'none', or change the visibility. But this is much slicker. With compatible browsers (IE and Mozilla/FireFox) it fades the object in or out at the rate that you specify

This code works by dynamically changing the opacity for an object, using either mozOpacity or an alpha filter in IE. It uses a scrip Timeout to perform the fade over time.

var ie5 = ( document.getElementById && document.all );
var moz = ( document.getElementById &&! document.all );
var opera = ( navigator.userAgent.indexOf( 'Opera' ) != -1 );
if ( opera ) ie5 = false;

var objInUse = "
var dirInUse = "
//parameters: objID = the object ID, dir: 'show' or 'hide
function fader( objID, dir ) {
if ( dirInUse != " && dirInUse != dir ) {
clearTimeout( goIn );
dirInUse = ";
}
if ( objInUse != " && objInUse != objID ) {
MM_findObj( objInUse ).style.visibility = 'hidden';
MM_findObj( objInUse ).style.display = 'none';
objInUse = ";
}

var obj = MM_findObj( objID );

if ( ie5 || moz ) {
obj.style.visibility = 'visible';
obj.style.display = 'block';
var fade_index;
dirInUse = dir;
objInUse = objID;

if( ie5 ) {
fade_index = obj.filters.alpha.opacity;
}
if( moz ) {
fade_index = obj.style.MozOpacity * 100;
}

fade_index = dir == 'show' ? fade_index + 5 : fade_index – 5;
index_limit = dir == 'show' ? 100 : 0;

if( ie5 ) {
obj.filters.alpha.opacity = fade_index;
}
if( moz ) {
obj.style.MozOpacity = fade_index / 100;
}
goIn = setTimeout( 'fader( \" + objID + '\', \" + dir + '\' )', 20 );
if( ( dir == 'show' && fade_index >= index_limit ) || ( dir == 'hide' && fade_index <= index_limit ) ) { //reached limit dirInUse = ''; objInUse = ''; clearTimeout( goIn ); if ( dir == 'hide' ) obj.style.display = 'none'; } } else { var strVis = dir == 'show' ? 'visible' : 'hidden'; var strDid = dir == 'show' ? 'block' : 'none'; obj.style.visibility = strVis; obj.style.display = strDis; } } function MM_findObj(n, d) { //v4.01 var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i

Share

3 Comments

  1. This is slick but does not work in ie6. Do you have a patch? Does this work on safari too?

  2. It worked for me in IE6. I'm not sure why it wouldn't work for you. Were you trying it on a local HTML file? If so, try uploading it or running it through a webserver, that may fix it

  3. Hey, Is there a link to the entire javascript code? Or is there an example of what the html looks like?
    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image