Javascript help

PixelPusher

Super Moderator
Staff member
Hi,
I have this simple code that fades a div in and out. The fadeIn works fine, however, the fadeOut only works with the alerts in place. See code:

HTML:
<script type="text/javascript">
var myObj;

function fadeIn() {
myObj = document.getElementById("fadeDiv");
	for (i=0; i<11; i++) {
		alert(i);
		setTimeout("setOpacity("+i+")", 100*i);
		}
	var i = "";
}

function fadeOut() {
myObj = document.getElementById("fadeDiv");
	for (i=10; i>=0; i--) {
		alert(i);
		setTimeout("setOpacity("+i+")", 100*i);
		}
	var i = "";
}

function setOpacity(value) {
	alert(value);
	myObj.style.opacity = value/10;
	myObj.style.filter = "alpha(opacity=" + value*10 + " )";
}

</script>
</head>

<body>
<div id="fadeDiv" style="background-color:#006699; border:double #003366 2px; width:100px; height:100px; position:relative; top:200px;">
<div style="color:white; font:bold 15pt Times; text-align:center; margin-top:30px; height:95px;">Opacity</div>
</div>
<a href="javascript:fadeIn()">Fade In</a><br/>
<a href="javascript:fadeOut()">Fade Out</a>
</body>

If you comment out the alert in the fadeOut() function the values starting counting up from zero instead of down from 10, even though the loop is set to count down. What am I not seeing? Thanks.
 
Last edited:

jnjc

New Member
At a guess I'd say the issue here is to do with using 'setTimeout', I reckon that the tasks are being queued so quickly that they are not executing in the correct order and thus causing the JS parser to get 'confused'. When you put alerts in, it is causing a gap between when each 'setTimeout' task is queued (while you click ok) and thus everything works fine. If it were me I'd get rid of the 'setOpacity' function and have 'setFadeIn' and 'setFadeOut' functions, which do the entire loop. Then in the 'Fadin' function use setTimeout to call the 'setFadeOut' function once.

HTH,
JC
 
Top