Javascript fade in and fade out effect - with pure Javascript

Here is the famous javascript that you can use to fade in and fade out an alert box area on your web page . The fade in and fade out function is being called through a button using the onclick event handler. Apart from this, you can also make a call to the fading function through your own code sequence at any given instance of events or conditions.

====================================
Put the following in the head of your html page :

<script>
Var TimeToFade = 900.00;

Function fade(eid)
{
var element = document.getElementById(eid);
if(element == null)
return;

if(element.FadeState == null)
{
if(element.style.opacity == null
|| element.style.opacity == ''
|| element.style.opacity == '1')
{
element.FadeState = 2;
}
else
{
element.FadeState = -2;
}
}

if(element.FadeState == 1 || element.FadeState == -1)
{
element.FadeState = element.FadeState == 1 ? -1 : 1;
element.FadeTimeLeft = TimeToFade - element.FadeTimeLeft;
}
else
{
element.FadeState = element.FadeState == 2 ? -1 : 1;
element.FadeTimeLeft = TimeToFade;
setTimeout("animateFade(" + new Date().getTime() + ",'" + eid + "')", 33);
}
}

Function animateFade(lastTick, eid)
{
var curTick = new Date().getTime();
var elapsedTicks = curTick - lastTick;

var element = document.getElementById(eid);

if(element.FadeTimeLeft <= elapsedTicks)
{
element.style.opacity = element.FadeState == 1 ? '1' : '0';
element.style.filter = 'alpha(opacity = '
+ (element.FadeState == 1 ? '100' : '0') + ')';
element.FadeState = element.FadeState == 1 ? 2 : -2;
return;
}

element.FadeTimeLeft -= elapsedTicks;
var newOpVal = element.FadeTimeLeft/TimeToFade;
if(element.FadeState == 1)
newOpVal = 1 - newOpVal;

element.style.opacity = newOpVal;
element.style.filter = 'alpha(opacity = ' + (newOpVal*100) + ')';

setTimeout("animateFade(" + curTick + ",'" + eid + "')", 33);
}
</script>

=======================

Put THE FOLLOWING IN THE BODY OF YOUR WEB PAGE :

<div id="fadebox" style="background-color:#ccddee;width:300px;height:150px;text-align:center;">
Add YOUR CONTENT HERE
</div>
Use the button below to fade in and fade out with the above javascript function :<br>
<button onclick="fade('fadebox');">Javascript Fade In and Fade Out!</button>

======================
This script uses pure javascript functionality to create fade effects. You don't need any advanced javascript library such as jquery or script.aculo.us or any ajax based javascript package.

There are nice little javascript jobs and freelance projects available on various freelancing websites on the internet. Whenever you need any such fading effect on any of your freelancing jobs, you can use this pure simple javascript with ease.

So enjoy nice fading with this javascript!

Filed Under Javascript on 11/06/2009 | Send 2 Friend | Print  

Shoot your comments on Javascript fade in and fade out effect - with pure Javascript...

(required)

(required)


Comments »

No comments yet.