...

View Full Version : Resolved js animation function half works, cant understand why other half doesnt



mike182uk
06-21-2009, 08:36 AM
hey there everyone

iam either being really dumb or something is way wrong with the code. i am trying to create a fade in / fade out effect. i know there are tons of scripts out there that do this, but i like to do it myself. my script is only working in firefox at the mo (when it works il cater for other browsers). basically i can get the fade out part to work, but when i want to fade back in it does nothing. now logically id of thought that fading in would be the same as fade out but reversed.



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<script type="text/javascript">

var status = 1;

function fade(){

var status;
var e = document.getElementById("test")
animate(e);

}

function animate(e){
if(status == 1){ //fade out
if(e.style.opacity == 0.1){
status = 0;
clearTimeout;
return;
}
else {
e.style.opacity = e.style.opacity - 0.1;
setTimeout( function(){ animate(e) }, 15 )
}
}

if(status == 0){ //fade in
if(e.style.opacity == 1){
status = 1;
clearTimeout;
return;
}
else {
e.style.opacity = e.style.opacity + 0.1;
setTimeout( function(){ animate(e) }, 15 )
}
}
}

</script>

</head>

<body>

<div id="test" style="width:200px; height:200px; background-color:#F00; opacity:1;" onclick="fade()"></div>
</body>
</html>



fading out works a treat. but getting it to fade back in just wont work. am i missing something really obvious here?

mike182uk
06-21-2009, 09:16 AM
hahaha yeh looking at it i am being dumb.

to be honest it shouldnt of worked at if you ask me (the fadeout). but somehow it does.

anyway heres what ive dun if any1 is interested lol




var status = 1;
var opacity = 100;

function fade(){

var e = document.getElementById("test")
e.style.opacity = opacity

animate(e);

}

function animate(e){
if(status == 1){
if(opacity == 0){
status = 0;
clearTimeout;
return;
}
else {
opacity = opacity - 10;

setTimeout( function(){ animate(e) }, 15 )
}
}

if(status == 0){
if(opacity == 100){
status = 1;
clearTimeout;
return;
}
else {
opacity = opacity + 10;

setTimeout( function(){ animate(e) }, 15 )

}
}

e.style.opacity = opacity / 100
}




instad of trying to alter the style.opacity which technically is a string, i just create a counter, that is then converted to a suitable opacity value and the style.opacity is set to this value.

mike182uk
06-21-2009, 09:23 AM
and to make it cross browser



e.style.filter = 'alpha(opacity=' + opacity + ')';



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum