PDA

View Full Version : Resolved Javascript fade in&out (without jquery)



keyboard
09-05-2012, 09:05 AM
Hello all!

I currently havae this code -


function fadeout(elem, time) {
elem = document.getElementById(elem);
var startOpacity = elem.style.opacity || 1;
elem.style.opacity = startOpacity;

(function go() {
elem.style.opacity -= startOpacity / (time / 100);

// for IE
elem.style.filter = 'alpha(opacity=' + elem.style.opacity * 100 + ')';

if(elem.style.opacity > 0) {
setTimeout(go, 100);
} else {
elem.visible = 'false';
}
})();
}

Which I'd like to convert so I also have a fadein() function, but not sure how :\
Any tips (Yes, I know you can do this with jquery, I'm trying to avoid that).
Also, is there any way to make the fade smoother?
keyboard1333

vwphillips
09-05-2012, 10:15 AM
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<title></title>
<script type="text/javascript">
/*<![CDATA[*/

function zxcFade(id,t,ms){
var obj=document.getElementById(id),o=zxcFade['zxc'+id],f;
if (obj&&!o){
o=zxcFade['zxc'+id]={ };
}
if (o){
clearTimeout(o.dly);
f=o.now||0;
t=typeof(t)=='number'&&t>=0&&t<=100?t:0;
animate(o,obj,f,t,new Date(),(ms||1000)*Math.abs(f-t)/100+5);
}
}

function animate(o,obj,f,t,srt,mS){
var oop=this,ms=new Date().getTime()-srt,now=(t-f)/mS*ms+f;
if (isFinite(now)){
obj.style.filter='alpha(opacity='+now+')';
obj.style.opacity=obj.style.MozOpacity=obj.style.WebkitOpacity=obj.style.KhtmlOpacity=now/100-.001;
o.now=now;
}
if (ms<mS){
o.dly=setTimeout(function(){ animate(o,obj,f,t,srt,mS); },10);
}
}


/*]]>*/
</script></head>

<body onload="zxcFade('tst');">
<img id="tst" src="http://www.vicsjavascripts.org.uk/StdImages/Egypt5.jpg" alt="img" onmouseup="zxcFade('tst',0,1000)" />
<input type="button" name="" value="Fade In" onmouseup="zxcFade('tst',100,1000);"/>
<input type="button" name="" value="Fade Out" onmouseup="zxcFade('tst',0,500);"/>


</body>

</html>