<-- Back -- Feedback

Fade-in/Fade-out Toggling


Introduction
Implementation
Conclusion

Introduction

As many have noticed and experienced, minor effects such as a simple fade-in or fade-out can do wonders for one's design. Although it is a good idea not to over-use nifty things such as fading, as some unneededly implement it "just because its cool", it can be a great asset providing it does not impare the end-user experience.

Additionally, it is wise to keep in mind that as the element(s) you fade in/out get larger and/or more complex, the client processing power required to execute the fade(s) will become even greater.

Implementation

Anyway, here is a quick and hopefully easy method of fading in and fading out effects(of divs, etc.) using Javascript.

Control of fading in and fading out with be done using a fade('id') function. This primary fade function will detect if the element is visible, and based upon those results, run fadeout() or fadein() 22(?) times in increasing intervals of time. fadeout() and fadein() will then make the opacity changes as requested, and if the opacity reaches a certain point, change the visibility.

The code would be as such:
fade.js
function fade(id) {
	var j = 0;
	if (document.getElementById(id).style.visibility != "hidden") {
		for (var i=22;i>=0;i--) {
			j++;
			setTimeout('fadeout('+id+', '+i+')',50*j);
		}
	} else {
		for (var i=0;i<22;i++) {
			j++;
			setTimeout('fadein('+id+', '+i+')',50*j);
		}
	}
}

function fadein(id, opacity) {
	if (opacity >= 1) {
		id.style.visibility = "visible";
	}
	id.style.opacity = opacity/10;
	id.style.filter = 'alpha(opacity='+opacity*10+')';
}

function fadeout(id, opacity) {
	id.style.opacity = opacity/10;
	id.style.filter = 'alpha(opacity='+opacity*10+')';
	if (opacity <= 1) {
		id.style.visibility = "hidden";
	}
}
Then, the HTML implementation would be as simple as:
<a href="javascript:;" onClick="fade('change');">Click to Fade in/out</a>
<div style="width:256px;border:1px solid #CCCCCC;padding:32px;" id="change">
Woooooo
</div>
Our end result should then be somewhat similar to the following:
Click to Fade in/out
Woooooo

Conclusion

When implementing fade effects, be sure that your design is functional even without Javascript. In particular, if you want to have effects start out blank, then fade in, put this small check in place:
<script type="text/javascript">
document.getElementById('nameofid').style.visibility = "hidden";
</script>
You can either place this change to a body onLoad, or immediately after the element is declared. By doing this, you easily make your design functional to those who may not be able to use the fade functions.

0.0045120716094971 µs