Javascript Tutorial - Simple Fade Animation

Skill

Javascript Tutorial - Simple Fade Animation

Posted in:

Woohoo fading! Everyone loves fading in and out, it is an excellent way to transition between two segments of an application (unless the fade takes too long, and then it just gets annoying). Today we are going to look at a simple and robust way of creating a fade in or fade out effect using javascript and the simple css 'opacity' element.

In the example below, you can see a green box with some text, and a button beneath it. If you press the button, the green box will fade out and become fully transparent, and if you press the button a second time, the box will fade back in. As you can see with the text inside of the box, anything that is a child of the fading element will also fade away/fade back. And, if you've clicked the button enough times, you've probably noticed that if you click it while the box is fading in one direction, it will flip and start fading in the opposite direction.



I'm Some Text

So how is all of this done? Well, it is actually pretty simple - we are doing an animation across the 'opacity' css element. We have done animation enough times in javascript in various tutorial on the blog that the code below will probably give you a sense of deja-vu. This is because the structure is very similar to some of the other animation code that we have done here, especially Accordion menus. Below, we have the function that kicks off the fade animation. I'll explain what it does after the code:

var TimeToFade = 1000.0;

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);
  }  
}

This fade function takes an element id, and the first thing we do is resolve it into an element object. The next thing we do is try to resolve its current 'FadeState', which is a property that this function will creates on the element when fade is called on that element for the first time. FadeState is one of 4 numbers - 2 means that the element is fully opaque, 1 means that the element is currently fading from transparent to opaque, -1 means that the element is currently fading from opaque to transparent, and -2 means that the element is fully transparent. If the FadeState property doesn't exist, we try and determine it from the state of the opacity css element.

If the FadeState is 1 or -1, it means that an animation is currently in progress. To flip the animation's direction, we flip the fade state, and flip the amount of time left to do the animation. So say we had an element that was fading out (a FadeState of -1), and we had 50 milliseconds left in the animation (out of a total of 500). If fade was called again on the element at that time, the FadeState would be flipped to 1 and the time left would be flipped to 450 (i.e., 500 - 50).

Otherwise, if the element is not currently fading in either direction, we set the fade state appropriately (if its opaque, we want to go to transparent, and if its transparent we want to go opaque), set the time to fade (FadeTimeLeft) to the full amount, and call setTimeout on the fade animation function. And this leads us right into the next chunk of code, the animateFade function:

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);
}

As always, the first thing we do inside an animation function is figure out how much time has passed since the animation was last updated. If this amount of time is more than the amount of time left in the animation, we set the element's opacity to the final value (fully transparent if the fade state is -1, and fully opaque if the fade state is 1), and then we return out.

So how do we actually set opacity? Well, for Firefox, Safari, and Opera, it is the CSS element 'opacity'. When 'opacity' is set to 0, the it means fully transparent, and when it is set to '1' it means fully opaque. Of course, IE does something completely different. For opacity in Internet Explorer, you have to set the 'filter' CSS element. And of course, you can't set it with the same values as the opacity element. For IE, "alpha(opacity=0)" is the value to set something transparent, and "alpha(opacity=100)" is how to set something opaque.

Back to the function at hand. Well, if we aren't out of time in the animation, we figure out what percentage opaque we are supposed to be at this current time in the animation. This is accomplished by a simple division of the amount of time left over the total amount of time in the animation. If you are fading out, this is the the new opacity value, and if you are fading in, the new value is 1 minus this figure.

Then, all we need to do is set the new opacity value, and then set another setTimeout to continue the animation.

I bet your wondering now about the html behind the example above. Well, as you can see below, there is virtually nothing there:

<div id="fadeBlock" style="background-color:Lime;width:250px;
      height:65px;text-align:center;">

  <br />
  I'm Some Text
</div>
<br />
<br />
<input type="button" onclick="fade('fadeBlock');" value="Go" />

The only important part is that the click handler for the button calls the fade function with the appropriate element id - in this case 'fadeBlock'.

That is it for doing a simple fade in/fade out animation in javascript. If anyone has any questions they should leave a comment below.

JaredC
12/26/2007 - 10:05

Hi there,

How would you make the box disappear after fading away? (eg. display = none)

Thanks

reply

Wutter
02/07/2011 - 09:16

Use this..

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;
element.innerHTML = "";
return;
}

reply

Vikas
01/13/2008 - 23:43

Dear Sir,

Thanks for the code. But what if I have a set of 5 or more text boxes and want them to appear one after another at an interval of say 20 seconds in a loop.

That is I do not want that the user should press the 'GO' button for the effect to take place, rather it should keep happening on the page automatically

Thanks in advance for the support.

reply

Penguinking
01/14/2008 - 16:50

ie4 = ((navigator.appVersion.indexOf("MSIE") > 0)
    && (parseInt(navigator.appVersion) <= 4));

var count = 0, count2 = 0, add1 = 3,
    add2 = 10, timerID;

function show()
{
  if (ie4)
  {
    count += add1;
    count2 += add2;
    delay = 30;
    if(count2 > 100)
      count2 = 100;
    if(count > 100)
    {
      count = 100;
      add1 = -10;
      add2 = -3;
      delay = 350;
    }
    if(count  

look im flashing!

there is something like you requested vikas but i havent been able to figure out how to get the time changing in there so it says something else after a matter of time. also tell me if u see any flaws in the code ty.

reply

Anonymous
06/04/2010 - 15:07

the hide function of css might do the trick....

reply

Penguinking
01/14/2008 - 16:51

opps lol it read it as code.

reply

Fouad Masoud
02/18/2008 - 02:14

Gr8 work there.
but i noticed a bug in IE (counts for 7 and 6) if you remove the height specified as inline style on the faded element it stops the fade any idea why ?

reply

Shadwick
02/25/2008 - 21:47

This works great! I tried but couldn't find how to make it so that it will fade to a 50% opacity minimum... could you tell me what change to make because I couldn't figure it out. Thanks!

reply

The Tallest
02/26/2008 - 07:22

Sure. You'll need to do two things. First, you need to modify the where the final values are set. Instead of:

element.style.opacity = element.FadeState == 1 ? '1' : '0';
element.style.filter = 'alpha(opacity = '
    + (element.FadeState == 1 ? '100' : '0') + ')';

You need to say:

element.style.opacity = element.FadeState == 1 ? '1' : '0.5';
element.style.filter = 'alpha(opacity = '
    + (element.FadeState == 1 ? '100' : '50') + ')';

Next, to fix what happens during the animation, what you need to do is modify newOpVal after it has been calculated, but before it is used to set the opacity. So instead of this:

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

You need to say something like:

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

And now you should be all set.

reply

Shadwick
02/26/2008 - 20:28

Thanks you so much! This works great.

reply

shazam-fu
07/01/2010 - 12:47

I didn't read down the page & basically did the same thing w/ a minor variation.

This part was the same:
element.style.opacity = element.FadeState == 1 ? '1' : '0.5';
element.style.filter = 'alpha(opacity = '
+ (element.FadeState == 1 ? '100' : '50') + ')';

And I added this part right below

if(element.FadeState == 1)
newOpVal = 1 - newOpVal;

if(element.FadeState == -1 && newOpVal <= 0.5){
element.FadeState = -2;
return;
}

reply

Anonymous
11/06/2010 - 08:39

I didn't read down the page & basically did the same thing w/ a minor variation.

This part was the same:
element.style.opacity = element.FadeState == 1 ? '1' : '0.5';
element.style.filter = 'alpha(opacity = '
+ (element.FadeState == 1 ? '100' : '50') + ')';

And I added this part right below

if(element.FadeState == 1)
newOpVal = 1 - newOpVal;

if(element.FadeState == -1 && newOpVal <= 0.5){
element.FadeState = -2;
return;
}

reply

Peter
03/05/2008 - 19:16

Thank you for this! It worked great for a prototype I was doing. I had to modify it as follows:

1) starts invisible and fades up
2) fades up to .8 and back to 0
3) added switches for style.display (answers JaredC's initial request)

Note that in my case the initial css on the element also needs to be set appropriately. Here's my modified code:

var TimeToFade = 250.0;

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 == '0.8')
    {
      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;
    element.style.display = element.FadeState == 2
        ? 'none' : 'block';
    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.display = element.FadeState == 1
        ? 'block' : 'none';
    element.style.opacity = element.FadeState == 1
        ? '.85' : '0';
    element.style.filter = 'alpha(opacity = '
        + (element.FadeState == 1 ? '85' : '0') + ')';
    element.FadeState = element.FadeState == 1 ? 2 : -2;
    return;
  }
 
  element.FadeTimeLeft -= elapsedTicks;
  var newOpVal = element.FadeTimeLeft/TimeToFade;
  if(element.FadeState == 1)
    newOpVal = 1 - newOpVal;

  newOpVal = newOpVal*0.85;
  element.style.opacity = newOpVal;
  element.style.filter =
      'alpha(opacity = ' + (newOpVal*100) + ')';
 
  setTimeout("animateFade(" + curTick
      + ",'" + eid + "')", 33);
}

#elementid {
  filter: alpha(opacity=0);
  -moz-opacity: 0;
  display:none;
}

If I were to use this for production code, I might implement variables for the direction and min/max opacity.

Good site guys. I'll be back!

reply

Dazed
09/07/2008 - 13:30

if Peter's code would work i'd appreciate it, i tried replacing everything but it just doesn't work, what i want is something that fades IN on the first try, then fades out when the fade function is used again.

reply

Shaw
02/27/2009 - 15:39

I modified this code in a couple of ways that I personally needed.

1. Instead of display: none / block (which causes elements around to be shifted whenever the content fades in), I switched it to visibility: hidden / visible.

2. The script now only fades in, and will not fade out. This is on purpose, because I wanted some content to fade in when the page loaded, but the user could click a link to show it instantly. Previously, if they clicked that link prematurely, the content would fade out when it was normally scheduled to fade in.

var TimeToFade = 2000.0;

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;
    element.style.visibility = element.FadeState == 2
        ? 'hidden' : 'visible'; // Switch visibility style rather than Dislay
    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.visibility = element.FadeState == 1 ? 'visible' : 'hidden'; // Switch visibility style rather than Dislay
    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; // This code is commented out to prevent a fade out
    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);
}

If you don't need these changes, then use the other code examples. If you know of a better way to implement it, please share!

reply

Pawan Soni
05/11/2008 - 22:31

really its very good idea for using opacity ....

thanks my problem has solved

reply

Human
05/23/2008 - 10:16

Hey, sweet little bit of code. I'm not a programmer by nature;rather a designer. My question is, is it possible to "inject" this code into Spry Sliding panels so they fade instead of sliding? Or, using them on their own, have the current visible block of info fade into the next block of info when a different button is clicked?

Thx in advance either way :P)

reply

Tim van Elsloo
05/29/2008 - 08:07

It was very handy,
Thank you very much!

reply

Rajashri
05/30/2008 - 00:26

This is for line

setTimeout("animateFade(" + new Date().getTime() + ",’"
    + eid + "‘)", 33);

Can I do it without the new Date().getTime()? just manually giving the milliseconds and incrementing it?
Thanks

reply

Roy
06/24/2008 - 22:56

Hey, I'm still messing around with the code, but is there a way to set it to 0 on start, then to 100?

I'm trying to set this as something that fades in on click, i have the CSS style set to "display:none" but that kills the whole thing... any ideas how to reverse it?

sorry if it is stated somewhere, i'll re-read this whole page once more also.

reply

Roy
06/24/2008 - 23:58

Okay, figure out my last issue,

now to read more, unless someone can answer how to use this on multiple id's like i have multiple div's I want to fadein/out but not using the same onclick.. so they are all seperated...

and my quest begins

reply

Roy
06/25/2008 - 00:02

okay, love the script, figure otu everything i need to know.. but

how do i actually get rid of the divs, 'cause even though transparent, they are taking up space and blocking other things.

any ideas?

reply

Anonymous
09/23/2010 - 14:08

Roy,

I am trying to set the text box to 0 on start and make it fade to 100 once you click on it the first time. Can you help me with this?

reply

Mohit
07/17/2008 - 18:01

how can i use a image to fade out and another image to fade in after fadding out the first one on click a button

please advice
Mohit

reply

Ryno
07/18/2008 - 08:31

Lets say i want to fade from 40 to 100 and back to 40 ??

reply

Ryno
07/18/2008 - 08:40

NVM i got it .. just put newOpVal += 0.4;

reply

Ryan
08/27/2008 - 20:17

For those who want to remove the element after fading out, just use:

document.body.removeChild(element);

just before the return; in function "animateFade".

reply

Anonymous
02/05/2011 - 08:05

Wouldn't another option be to use absolute positioning with a high z-value for the element in question? This would place it on top of other content (while taking it out of the natural document flow). Then, when it faded, your content behind it would be revealed.

reply

Julian
08/28/2008 - 07:21

i first tried some stuff and changed the code by myself... then i saw that this was already disscussed and copyied it but it was exactly the opposit from what i wanted to get :D

i wanted to fade from 0 to 50
and then back to 0

but now i changed and changed things arround and it doesn't start at 50 it allways goes to full opacity on fadeout...
this sucks :D
can someone help me out with that problem??

here is the code i had...

function timmer (status) {
  document.getElementById("timmerhg").style.visibility =  
    status;
}

var TimeToFade = 1000.0;

function fade(status)
{
  var element = document.getElementById(status);
  if(element == null)
    return;
           
  if(element.FadeState == null)
  {
    if(element.style.opacity == null
        || element.style.opacity == '0.5'
        || element.style.opacity == '')
    {
      element.FadeState = -2;
    }
    else
    {
      element.FadeState = 2;
    }
  }
           
  if(element.FadeState == 0.5 || element.FadeState == -0.5)
  {
    element.FadeState = element.FadeState == 0.5 ? -0.5 : 0.5;
    element.FadeTimeLeft = TimeToFade - element.FadeTimeLeft;
  }
  else
  {
    element.FadeState = element.FadeState == 2 ? -0.5 : 0.5;
    element.FadeTimeLeft = TimeToFade;
    setTimeout("animateFade(" + new Date().getTime()
        + ",'" + status + "')", 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 == 0.5
        ? '0.5' : '0';
    element.style.filter = 'alpha(opacity = '
        + (element.FadeState == 0.5 ? '0.5' : '0') + ')';
    element.FadeState = element.FadeState == 0.5 ? 2 : -2;
    return;
  }
         
  element.FadeTimeLeft -= elapsedTicks;
  var newOpVal = element.FadeTimeLeft/TimeToFade;
  if(element.FadeState == 0.5)
    newOpVal = 0.5 - newOpVal;
       
  element.style.opacity = newOpVal;
  element.style.filter =
      'alpha(opacity = ' + (newOpVal*50) + ')';

  setTimeout("animateFade(" + curTick
      + ",'" + status + "')", 33);
}

reply

Enne87
09/09/2008 - 13:58

I would like to use an imagebutton instead of a normal button, but when I change attribute "type=input" to "type=image", the rectangle disappears and immediately appears.

reply

Stikiflem
09/11/2008 - 03:57

hey guys, i tweaked the fading a bit. It will start Fading In, then Fading Out - the opposite. I know it was already explained at the top but my tiny little brain got confused and i wasted some time on it. I won't post it here because its a pain in the as* with the quotes and other characters. Here's the link instead. (hope the author dont mind).

Thanks again for all the help! The codes above really helped me :)

reply

Ghprod
09/24/2008 - 14:13

great!

so simple but powerful ... :)

Thnx

reply

Doez
11/08/2008 - 08:27

thank's

reply

Tabrizz
02/11/2009 - 22:12

Do you know how to use multiple DIV ID's with different buttons/links? For example, I want to use 2 separate links that call this function, and when I click one link it makes one DIV transparent (invisible) before making the second opaque (visible).

reply

Reda
03/02/2009 - 07:40

Thank you so much for this amazing and useful script!
I have just one question please:
i have an invisible item (

image...

)
and i want to apply the fade in when i make it visible...
i'm not good in JS, how can i do that?
Thanks a lot

reply

Kempison
03/04/2009 - 17:44

Hi. What attribute can I change/add to delay the initial fade in? I want another action to finish before this one commences. Thanks in advance for any help given.

reply

Anonymous
04/12/2009 - 02:47

hi

reply

Anonymous
04/16/2009 - 09:52

Can someone post the code to fadeout also. The current code just fades in but not fadeout.

Thanks

reply

James
06/08/2009 - 09:39

Great code!
I trying to modify the code so it starts 0% then fades in to 100%

Can someone assist me please.

reply

James
06/08/2009 - 09:56

solved it,
Thanks anyway

again great code!

reply

Magnus J
06/23/2009 - 06:03

Hi, great code!!!
Like "Tabrizz" said:
How can you get this to hide the currently visible layer when opening a new one? That would be really useful.

Anyone?

reply

Tory
06/24/2009 - 23:51

HI nice script man! However, I am wondering how I can customize this like for example I have 3 hidden div's with contents and each has it's own link for toggling it's visibility, so clicking Link1 for example shows Div1 but hides Div2 and 3. Then clicking Link2 show Div2 but hides Div1 and Div3 so on. Of course the default visible is Div1 which the hiding and the showing is controlled by the fading script you have above...

I think this would be a nice application to it, appearing like a pseudo-AJAXy feel to content control...

reply

earlt777@hotmail.com
08/15/2009 - 00:23

Thank you so much for this code. I would have been lost as to where to even start to accomplish this.

I made a few minor tweeks to get it to have independent fade in / fade out with seperate fade values and time delay.

If you find bugs or improvements, please let me know.

Earl

Here is the Code:

function fadeX(objToFadeID, IsFadeIn, timeToFade, delay)
{
//objToFadeID - Object ID of the Div or object you want to fade
//IsFadeIn - Is this a fade in (vs fade out) 1 = true, 0 = false
//timeToFade - Time in ms to fade the object
//delay - Time in ms to delay the fade

var objToFade = document.getElementById(objToFadeID);
if(objToFade == null)
return;

var fadeXFactor = IsFadeIn==1?1:-1; // used to reverse values for fade in vs out

if ((timeToFade==0)&&(delay==0))
{
//if this is a simple instant popup, then make the settings are return
objToFade.style.opacity = 1*IsFadeIn;
objToFade.style.filter = 'alpha(opacity = ' + 100*IsFadeIn + ')';
objToFade.fadeState=2*fadeXFactor;
return;
}

if (delay == null)
delay = 0;

if (IsFadeIn)
objToFade.OriginalFadeInTime = timeToFade;
else
objToFade.OriginalFadeOutTime = timeToFade;

if(objToFade.fadeState != null)
{

if ((objToFade.fadeState==1*fadeXFactor)||(objToFade.fadeState==2*fadeXFactor)||(objToFade.fadeState==3*fadeXFactor))
{
return; //Current fade is in same direction or already there so we are OK;
}
else if (objToFade.fadeState==-1*fadeXFactor)
{
//reverse the time and the fade direction and let it continue
objToFade.fadeState = 1*fadeXFactor;
objToFade.timeToFade = timeToFade;
if (IsFadeIn)
{
objToFade.fadeTimeLeft = timeToFade*(1-objToFade.fadeTimeLeft/objToFade.OriginalFadeOutTime);
}
else
{
objToFade.fadeTimeLeft = timeToFade*(1-objToFade.fadeTimeLeft/objToFade.OriginalFadeInTime);
}

return;
}
else if (objToFade.fadeState==-3*fadeXFactor)
{
//object is in hold status but directoin needs to be reversed and use the passed in time value
objToFade.fadeState=3*fadeXFactor;
objToFade.timeToFade = timeToFade;
if (IsFadeIn)
{
objToFade.fadeTimeLeft = timeToFade*(1-objToFade.fadeTimeLeft/objToFade.OriginalFadeOutTime);
}
else
{
objToFade.fadeTimeLeft = timeToFade*(1-objToFade.fadeTimeLeft/objToFade.OriginalFadeInTime);
}
return;
}
}

//if we got this far, then the object is in the fully opposite state
objToFade.timeToFade = timeToFade;
objToFade.fadeTimeLeft = timeToFade;
objToFade.fadeState = 3*fadeXFactor;
var now = new Date();
now.setMilliseconds(now.getMilliseconds() + delay);
setTimeout("animateFade(" + now.getTime() + ",'" + objToFadeID + "')", 10 + delay);
}

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

var element = document.getElementById(elementID);
if (element.fadeState==3) element.fadeState=1;
if (element.fadeState==-3) element.fadeState=-1;

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/element.timeToFade;
if(element.fadeState == 1)
newOpVal = 1 - newOpVal;
element.style.opacity = newOpVal;
element.style.filter = 'alpha(opacity = ' + (newOpVal*100) + ')';

setTimeout("animateFade(" + curTick + ",'" + elementID + "')", 10);
}

This is a test
reply

earlt777@hotmail.com
08/15/2009 - 00:28

And here is the HTML for the javascript code above:

<body>
<form id="form1" runat="server">
<div>
<div id="FadeBlack" style="background-color:Red; width:250px; height:100px; opacity:0 ;filter:alpha(opacity = 0);">
This is a test
</div>
<input id="Button3" type="button" value="Rollover" onmouseover="fadeX('FadeBlack',1,5000,1000)" onmouseout="fadeX('FadeBlack',0, 1000, 1000)" />
</div>
</form>
</body>

reply

darkRoom
12/29/2009 - 14:39

This is a great site I spent day's looking all over for this script and the edit(from Shaw) without success just a bunch of nonsense(although it did help my skills being new to JS) Thanks I'll be back

reply

uiman
03/07/2010 - 23:27

Thanks for the code, really liked the way you resolve it. I'm going to check the rest of the site...

BTW You should check the 'anti-SPAM' on Chrome, I think there something wrong...

reply

vio
03/09/2010 - 08:56

Thanks for that nice code!
I extended the code to specify min. and max. opacities and made it more compact by merging the two functions 'fade' and 'animateFade' to just one function again called 'fade'! Apart from that it behaves like the original code!

fadeTime = 500.0;

fadeMin = 0.0;
fadeMax = 1.0;

function fade(id, lastTick) {
        var tick = new Date().getTime();
        var element = document.getElementById(id);
        if (element.fadeState) {
                if (lastTick)
                        element.fadeTime += tick-lastTick;
                else {
                        element.fadeState = element.fadeState == 1 ? -1 : 1;
                        element.fadeTime = fadeTime-element.fadeTime;
                        return;
                }
        }
        else {
                element.fadeState = element.style.opacity == fadeMax ? -1 : 1;
                element.fadeTime = 0.0;
        }
        var opacity = element.fadeTime/fadeTime;
        if (element.fadeTime >= fadeTime)
                opacity = 1.0;
        if (element.fadeState == -1)
                opacity = 1.0-opacity;
        opacity = (fadeMax-fadeMin)*opacity+fadeMin;
        element.style.opacity = opacity;
        element.style.filter = 'alpha(opacity='+opacity*100+')';// IE
        if (element.fadeTime >= fadeTime)
                element.fadeState = null;
        else
                setTimeout("fade('"+id+"',"+tick+")", 33);
}

You have to call the function with just one argument, for example:

<img id="hover" src=".." style=".." onMouseOver="fade(this.id);" onMouseOut="fade(this.id);">

reply

vio
03/24/2010 - 20:39

Now you can specify different fade settings for each element.
Also asynchronous fading is possible.
The values in the code are just default values.

fadeTime = 400;
fadeMin = 0.0;
fadeMax = 1.0;
fadeRate = 20;

function fade(id, time, min, max, rate, lastTick) {
        var tick = new Date().getTime();
        var element = document.getElementById(id);
        if (element.fadeState) {
                if (lastTick)
                        element.fadeTimeElapsed += tick-lastTick;
                else {
                        element.fadeState = element.fadeState == 1 ? -1 : 1;
                        element.fadeTimeElapsed = element.fadeTime-element.fadeTimeElapsed;
                        if (time != null) {
                                element.fadeTimeElapsed = element.fadeTimeElapsed/element.fadeTime*time;
                                element.fadeTime = time;
                        }
                        return;
                }
        }
        else {
                element.fadeTime = time != null ? time : element.fadeTime != null ? element.fadeTime : fadeTime;
                element.fadeMin = min != null ? min : element.fadeMin != null ? element.fadeMin : fadeMin;
                element.fadeMax = max != null ? max : element.fadeMax != null ? element.fadeMax : fadeMax;
                element.fadeRate = rate != null ? rate : element.fadeRate != null ? element.fadeRate : fadeRate;
                element.fadeState = element.style.opacity == element.fadeMax ? -1 : 1;
                element.fadeTimeElapsed = 0.0;
        }
        var opacity = element.fadeTimeElapsed/element.fadeTime;
        if (element.fadeTimeElapsed >= element.fadeTime)
                opacity = 1.0;
        if (element.fadeState == -1)
                opacity = 1.0-opacity;
        opacity = (element.fadeMax-element.fadeMin)*opacity+element.fadeMin;
        element.style.opacity = opacity;
        element.style.filter = 'alpha(opacity='+opacity*100+')';// IE
        if (element.fadeTimeElapsed >= element.fadeTime)
                element.fadeState = null;
        else
                setTimeout("fade('"+id+"', null, null, null, null, "+tick+")", element.fadeRate);
}

Example for fading with default values:

<img id=".." src=".." style=".." onmouseover="fade(this.id);" onmouseout="fade(this.id);" onclick="fade(this.id);" />

The onclick event resets the fading. This is important when the image is a link. Otherwise the onmouseover and onmouseout events would be inverted after you hit the link and then go back with the browser button!

Example for fading with only max value as default:

<img id=".." src=".." style=".." onmouseover="fade(this.id, 1000, 0.2, null, 33);" onmouseout="fade(this.id);" onclick="fade(this.id);" />

The values need to be just specified by the first triggered event.

Example for asynchronous fading:

<img id=".." src=".." style=".." onmouseover="fade(this.id, 200);" onmouseout="fade(this.id, 2000);" onclick="fade(this.id, 2000);" />

By fading asynchronous you can't use default values for the fade time!

reply

Anonymous
07/05/2011 - 17:28

This code is amazing! Thank you. Is there a way to direct the page to load with the box faded out, so that clicking triggers a fade in?

reply

cow.bell21@yahoo.com
04/24/2010 - 19:56

This is great..But it is not working for IE 8 for me. Can you help. I used the exact code in vio's 03/09/2010 - 08:56 example

the only thing different was how i called the function.

and called the function using this:

<td onmouseover="fade('apple');" onmouseout="fade('apple');" onclick="fade('apple');" >

i would appreciate if you could show me what to do to make it work in IE 8. Again I used the exact code for the function part. I just copy pasted it. Please send me an email as well if you figured out how to fix this in IE 8. My email is my name :)

reply

cow.bell21@yahoo.com
04/24/2010 - 19:57

ahh the code didn't come up :( but i doubt my calling the function is messing it up for IE 8

reply

PKo
03/15/2010 - 01:14

Hi, there is nice code on this site.

I used the variant by earlt777@hotmail.com to install it with the 'onload' handler of the body tag.

This worked fine with Firefox/Opera, but it didn't work with IE8.

If I want to fade into a page with IE8, only the following header tags will have success:

Are there experiences to use some variant of the fading script here with body/onload on IE8?

reply

PKo
03/15/2010 - 01:28

In my last post I forgot the IE8 specific code, here it is:

<meta http-equiv="Page-Enter" content="progid:DXImageTransform.Microsoft.Fade(Duration=4)">
<meta http-equiv="Page-Exit" content="progid:DXImageTransform.Microsoft.Fade(Duration=3)">

reply

malicedix
03/21/2010 - 04:22

I would really like this code to fade out the currently visible div on my page when i click any link on the navigation menu, and then load in its place the div containing the content of the clicked link (which should be hidden by default).

Any one got a tweak to make this happen?

Thanks in advance

reply

james
03/21/2010 - 05:39

Can anyone help me with a chat code?

reply

SpaceProgramer
04/19/2010 - 16:12

Hello, can any buddy tell my how to get the fade block to be faded on page load?

reply

Newbie
09/23/2010 - 14:14

SpaceProgramer,

I am trying to do the same thing. Did you ever figure out how? Please let me know what I need to do in order to achieve this.

Thanks

reply

Postage33
04/24/2010 - 03:11

Like a few folks have asked so far, does anyone know how to adapt this so that it can be used for multiple DIVs? That is, let's say you had a menu of several links, and for every link there was an associated DIV.

ie:
When you click link 1, Div 1 would fade in. Then, when you click link 2, Div 1 would fade out and Div 2 would fade in.

That would be mega-useful and powerful to have. I've made a few stabs at it (I'm a total JS noob), but no luck yet.

Thoughts, ideas or suggestions anyone?

Thanks!

/this is seriously awesome code as it stands though! Thanks!

reply

ajaxender
05/19/2010 - 22:25

Hey thanks a lot for this code, its really good. I have somewhat blatantly ripped it off for my website :P so you are mentioned in the source. I edited it a little to make the fadeTime an extra parameter of the methods, so its set when called rather than being the same all the time, for every object.

to postage33 - this code is ideal for calling by other methods. For what you're talking about, I would make a method that calls fade on whatever div that corresponds to the link you clicked, and also calls fade on any divs that are not invisible. This should fade in the clicked div, while fading out any div that is visible, no matter if its fully faded in or not.
If you only have one div visible at a time, you just need a variable to keep track of what div was last clicked, so the method knows which other div to call fade on.

reply

neilime
06/15/2010 - 07:12

Here is my version, i guess i fixe 2 bugs
n°1 : fadeIn on an element which has " filter : alpha(opacity=0)" seems doesn't work

n°2 : fadeout on an element which contains elements which are on "position : absolute" seems doesn't work

 
function fadeElement(sElementId, fLastTick){
        var fFadeTime = 500.0;
        var fFadeMin = 0.0;
        var fFadeMax = 1.0;
       
        var eElement = document.getElementById(sElementId);
        if(!eElement)return;
       
        var fTick = new Date().getTime();  

    if(eElement.fadeState){
        if(fLastTick)eElement.fadeTime += fTick-fLastTick;
        else{
                eElement.fadeState = eElement.fadeState === 1 ? -1 : 1;
                eElement.fadeTime = fFadeTime-eElement.fadeTime;
                return true;
        }
    }
    else{
        if('undefined' !== typeof(eElement.style.opacity))eElement.fadeState = parseFloat(eElement.style.opacity) === fFadeMax ? -1 : 1;
        else{
                if('undefined' !== typeof(eElement.style.filter)){
                        var iIeOpacity = parseFloat(eElement.style.filter.replace('alpha','').replace('opacity','').replace('=','').replace(')','').replace('(',''))/100;                      
                        eElement.fadeState = iIeOpacity === fFadeMax ? -1 : 1;
                }
                else return false;
        }
        eElement.fadeTime = 0.0;
    }
    var fOpacity = eElement.fadeTime/fFadeTime;
    if(eElement.fadeTime >= fFadeTime)fOpacity = 1.0;
    if(eElement.fadeState == -1)fOpacity = 1.0-fOpacity;
    fOpacity = (fFadeMax-fFadeMin)*fOpacity+fFadeMin;
    eElement.style.opacity = fOpacity;
    eElement.style.filter = 'alpha(opacity='+fOpacity*100+')';// IE
    if(eElement.children.length>0){
        for(var i=0; i<eElement.children.length;i++){
                eElement.children[i].style.filter = 'alpha(opacity='+fOpacity*100+')';// IE
        }      
    }
    if(eElement.fadeTime >= fFadeTime)eElement.fadeState = null;
    else setTimeout("fadeElement('"+eElement.id+"',"+fTick+")", 33);
}

Ps : sorry for my english... i'm french

reply

android1
08/23/2010 - 05:27

Hi
Brilliant code - thanks.
Can anyone tell me how to modify it to fade only in one direction ie to make to separate functions, one for fade in, the other for fade out, which can be called independently.

reply

Anonymous
09/23/2010 - 14:12

I am a total newbie when it comes to JS so if someone could give me the code to make the animation not appear on start but fade to 100 once the button is clicked for the first time, that would be very helpful.

reply

Ram Kumaran
09/24/2010 - 08:31

Nice script, I liked it.

I feel you guys can help me get out of the problems below.
* element.fadeState, I was able to read and write values to this in firefox. But, it doesn't seem to work in IE.

* I wish to perform animation based on the element's current opacity to specified opacity. For this purpose I have to read the current opacity value, which is quite easy in all browsers except IE.

reply

The Reddest
09/24/2010 - 08:42

According the tutorial's text, element.style.opacity works in all browsers except IE. For IE it's element.style.filter.

reply

Ram Kumaran
09/25/2010 - 02:34

Thanks The Reddest for the quick response.

how to handle htmlelement.property? is there any other method to do it.

reply

jrbk
09/29/2010 - 15:08

I am not a coder. I have read through and don't see what I am looking for. I have this java script (seen below) and would like to add the fade effect to it. Any suggestions on how to do that?

 

}
var n = 0;
timedelay = 5;
timedelay *= 1000;
//windowprops = "top=250,left=15,width=200,height=200";
windowprops = "toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes"
var imgs = new Array();
imgs[0] = "images/1.jpg";
imgs[1] = "images/2.jpg";
imgs[2] = "images/3.jpg";
var page = new Array();
page[0] = "";
page[1] = "";
page[2] = "";



function hook() {
var p = (n == 0) ? page[page.length-1] : page[n-1];
window.open(p,"",windowprops);
//document.location.href=p;
}
function rotate() {
document.picform.slideshow.src = imgs[n];
(n == (imgs.length - 1)) ? n = 0 : n++;
window.setTimeout("rotate()", timedelay);
}
function MM_swapImgRestore() { //v3.0  
var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
 
function MM_preloadImages() { //v3.0  
var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array(); var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++) if (a[i].indexOf("#")!=0){ d.MM_p[j]

=new Image; d.MM_p[j++].src=a[i];}}
}
 
function MM_findObj(n, d) { //v3.0  
var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!

x&&i<d.forms.length;i++) x=d.forms[i][n];for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); return x;
}
 
function MM_swapImage() { //v3.0  
var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src;

x.src=a[i+2];}
}
window.onload = rotate;
//  End -->
//  End -->
<!--
function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);
// -->


function Require(obForm,szFields)
    {
      var fields = szFields.split(",")
      var szMissing= new Array();
      for (x=0;x<fields.length;x++) {
        if (obForm.elements[fields[x]].value.length==0) {
           szMissing[szMissing.length]=new String(fields[x]);
        }
      }
      if (szMissing.length) {
        alert("All fields are required");
        return false
      }
      return true; -IE
    }


function changeText2(){
        var userInput = document.getElementById('hisname').value;
        document.getElementById('hisher').innerHTML = userInput;
        return true;
}

function changeText1(){
        var userInput = document.getElementById('urname').value;
        document.getElementById('urname2').innerHTML = userInput;
        document.getElementById('urname3').innerHTML = userInput;
        return true;
}


function changeText3(){
        var userInput = document.getElementById('greeting').value;
        document.getElementById('greeting2').innerHTML = userInput;
        return true;
}

reply

mrrena
09/29/2010 - 19:51

There are two things I didn't like about the way you implemented this code: the fact you are storing a foreign attribute directly on the element and that you recurse using spliced-in variables. I wanted something more object-oriented without needing to install a framework.

But I otherwise thought the code had potential, so I'm offering my re-working back to everyone else. Note that the class-based approach also easily allows you to fade multiple elements at a time.

//declare our class so we can use the "new" keyword to create multiple instances
var animateFade = function(elmOrElmId, duration, state) {
        this.setOptions(elmOrElmId, duration, state);
};

//prototype its helper functions
animateFade.prototype = {
       
        setOptions: function(elmOrElmId, duration, state) {
               
                //set options
                this.fadeDuration = duration;
                this.element = (typeof elmOrElmId == 'string') ? document.getElementById(elmOrElmId) : elmOrElmId;
                this.fadeState = (state && state == 1) ? 1 : -1;//default -1 fade out, 1 fade in
                this.fadeTimeLeft = duration;//preset to passed duration, then overwrite
                this.lastTick = this.newTick();
               
                //start animation
                this.animate();
        },
       
        newTick: function() {
                return new Date().getTime();
        },
       
        returnElapsedTicks: function() {
                return this.currentTick - this.lastTick;
        },
       
        animate: function() {
               
                this.currentTick = this.newTick();
               
                var self = this;
                var elapsedTicks = this.returnElapsedTicks();
               
                //helper function, called in the timeout below, to recurse while maintaining correct reference of "this"
                var helper = function() {
                        self.animate();
                };
               
                if (this.fadeTimeLeft <= elapsedTicks) {
                        this.element.style.opacity = (this.fadeState == -1) ? 0 : 1;
                        this.element.style.filter = 'alpha(opacity = ' + (this.fadeState == -1) ? 0 : 100 + ')';
                        return;
                }
               
                this.fadeTimeLeft -= elapsedTicks;
               
                var newOptVal = this.fadeTimeLeft / this.fadeDuration;
               
                newOptVal = (this.fadeState == -1) ? newOptVal : (1 - newOptVal);
               
                this.element.style.opacity = newOptVal;
                this.element.style.filter = 'alpha(opacity = ' + (newOptVal * 100) + ')';
               
                this.lastTick = this.currentTick;
                this.currentTick = this.newTick();
               
                setTimeout(helper, 33);
        }
};

//initialize function
var init = function(elmsOrElmIdArr, duration) {
        for (var i = 0, l = elmsOrElmIdArr.length; i < l; i++) {
                //use "new" keyword to create separate instances
                new animateFade(elmsOrElmIdArr[i], duration);
        }
};

////////////////////
// USAGE EXAMPLES //
////////////////////

//pass in either id string or element reference

//Example A: fade just one element
var myOnlyElement = ['myUniqueId'];

//Example B: fade multiple elements
//var myMultElements = ['myId', document.getElementsByTagName('input')[7], 'my_other_id'];
var myMultElements = ['modal', 'popup'];

//how long fade should last
var myDuration = 1000;//1,000 milliseconds, or 1 second

//start fading
init(myMultElements, myDuration);

reply

mrrena
09/29/2010 - 19:59

Forgot to demonstrate that you could set your single or multiple elements to fade in by passing a 1. (Only really need two states, and fade out is the default state.)

init(myMultElements, myDuration, 1);//fade in

Omit the 1, as in the very last example in my previous post, to fade out.

reply

mrrena
09/30/2010 - 19:29

One last post with apologies: to make this work in IE, you will need to enclose the conditions in an extra set of parentheses.

If you prefer, just copy and paste. See where in my first post the comments indicate what the "helper" function does? Then see the "if" block immediately below that? Replace that "if" block with the following "if" (the top two lines inside the "if" statement contain the enclosing parentheses demanded by IE).

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

Also, if you want to fade in (as per my second follow-up post), you'll need to add in "state" to your initializer function--I failed to add it to the initializer example. Just replace it with the following:

var init = function(elmsOrElmIdArr, duration, state) {
        for (var i = 0, l = elmsOrElmIdArr.length; i < l; i++) {
                //use "new" keyword to create separate instances
                new animateFade(elmsOrElmIdArr[i], duration, state);
        }
};

Last, just a thought. Someone posted an apparently asynchronous solution above that allowed multiple elements to both fade in and out at the same time. There is absolutely no reason in the world you could not set all three things asynchronously--the element, the duration, and its state of fading in or fading out--with this class-based method.

Here's an example--if you want to try this approach, this is the initializer method all over again, this time taking advantage of multiple arrays:

var init = function(elmsOrElmIdArr, duration, state) {
        for (var i = 0, l = elmsOrElmIdArr.length; i < l; i++) {
                //use "new" keyword to create separate instances
                new animateFade(elmsOrElmIdArr[i], duration[i], state[i]);
        }
};

///BASIC IDEA TO IMPLEMENT

//in the example below, each array is the same length:
//elm1 fades out in 1 second
//elm2 fades in in 3/10ths of second
//elm3 fades out in 7/10ths of a second
var myElms = [elm1, elm2, elm3];
var myDurations = [1000, 300, 700];
var myState = [-1, 1, -1];
init(myElms, myDurations, myState);

Anyway. :)

reply

Bart van Diepen
11/16/2010 - 14:48

Great script, Thanks Mrrena

reply

kaipo
11/04/2010 - 09:37

hi

i like to cover the contents of my page

the script works but the links dont work

how to fix?

chico.woelmuis.nl/erasure/erasure.htm

thnx

reply

Anonymous
11/06/2010 - 13:45

Great stuff.

Similar to what Vikas asked earlier and wasn't answered satisfactory yet, I have about 5 texts that should fade in and fade out one after another (in the same space) at an interval of about 20 seconds in a loop.

So there will be no buttons or mouse-actions that trigger anything, but it happens all by itself on the page.

Thanks.

reply

Dan
12/09/2010 - 17:20

How would I set the code so that the image starts off transparent and then becomes opaque after clicking a button?

reply

Ian
01/19/2011 - 14:05

Dan, see my post, and the view the source code for the link. I simply inverted the:
element.FadeState = -2;
}
else
{
element.FadeState = 2;

making it:

element.FadeState = 2;
}
else
{
element.FadeState = -2;

now it fades in instead of out. But I have that problem I mentioned...

reply

Ian
01/19/2011 - 13:52

Loving this code! But one snag for me--I want things to be invisible and then fade into view--I can do that by having the fade triggered by body onload, but this makes them appear briefly before fading out when the page loads. I rather these elements not be seen at all until they are triggered by the user.

I've read through the comments and codes above, and can't find any that really do the trick. How do I make these things stay hidden until triggered?

Here's my test page:
http://ianmartinphotography.com/test-site/testimonials/prefade-test-01.html

Any help would be great!

reply

Anonymous
02/05/2011 - 08:08

You should be able to set the initial opacity of the div element to 0 in the stylesheet or html file. The function would then act to change it.

See if that works.

reply

John1986m
01/31/2011 - 04:06

Hi
Great code..Thanks a lot!
Can someone help on how i can fade out a link(or just text) for example and then at the same position fade in another link??

reply

Michael Knepprath
02/04/2011 - 21:19

I don't usually comment on stuff on the internet. But I felt that this was worth it. THANK YOU SO MUCH FOR THIS!!!!!!!!!!!!!!!!!!!!!!!!!!

reply

Anonymous
02/09/2011 - 18:10

great script ! thank you

reply

Guillaume
03/12/2011 - 16:14

hello I have a tooltip script as follows:

var xOffset=6
var yOffset=15    

var affiche = false; // La variable i nous dit si le bloc est visible ou non
var w3c=document.getElementById && !document.all;
var ie=document.all;

if (ie||w3c) {
  var laBulle
}

function ietruebody(){  // retourne le bon corps...
  return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function deplacer(e) {
  if(affiche){
    var curX = (w3c) ? e.pageX : event.x + ietruebody().scrollLeft;
    var curY = (w3c) ? e.pageY : event.y + ietruebody().scrollTop;

    var winwidth = ie && !window.opera ? ietruebody().clientWidth : window.innerWidth - 20;
    var winheight = ie && !window.opera ? ietruebody().clientHeight : window.innerHeight - 20;

    var rightedge = ie && !window.opera ? winwidth - event.clientX - xOffset : winwidth - e.clientX - xOffset;
    var bottomedge = ie && !window.opera ? winheight - event.clientY - yOffset : winheight - e.clientY - yOffset;

    var leftedge = (xOffset < 0) ? xOffset*(-1) : -1000

    // modifier la largeur de l'objet s'il est trop grand...
    if(laBulle.offsetWidth > winwidth / 3){
      laBulle.style.width = winwidth / 3
    }

    // si la largeur horizontale n'est pas assez grande pour l'info bulle
    if(rightedge < laBulle.offsetWidth){
      // bouge la position horizontale de sa largeur à gauche
    } else {
      if(curX < leftedge){
        laBulle.style.left = "5px"
      } else{
        // la position horizontale de la souris
        laBulle.style.left = curX + xOffset + "px"
      }
    }

    // même chose avec la verticale
    if(bottomedge < laBulle.offsetHeight){
      laBulle.style.top = curY - laBulle.offsetHeight - yOffset + "px"
    } else {
      laBulle.style.top = curY + yOffset + "px"
    }
  }
}
function montre(text) {
  if (w3c||ie){
    laBulle = document.all ? document.all["bulle"] : document.getElementById ? document.getElementById("bulle") : ""
    laBulle.innerHTML = text; // fixe le texte dans l'infobulle
    laBulle.style.visibility = "visible"; // Si il est cachée (la verif n'est qu'une securité) on le rend visible.
    affiche = true;
  }
}



function cache() {
  if (w3c||ie){
    affiche = false
    laBulle.style.visibility="hidden" // avoid the IE6 cache optimisation with hidden blocks
    laBulle.style.top = '-1000px'
    laBulle.style.backgroundColor = ''
    laBulle.style.width = ''
  }
}


document.onmousemove = deplacer; // des que la souris bouge, on appelle la fonction move pour mettre a jour la position de la bulle.

I'm not very talented, so you will it be possible to add the code needed to include the "fade function and restored me entirely coded please

Thank you in advance
Sincerely,
William
PS: sorry for the language but I'm French

reply

Jess
04/06/2011 - 09:55

Hi, I'm trying to get my main images to fade and be hyperlinked to specific pages. Could you help me? The page is: http://www.northland.edu/test

Thank you.

reply

Bim
05/23/2011 - 05:11

doing exactly the same!

want it for an image transition ill post when done

reply

Bim
05/23/2011 - 05:56

Hi Jess,

finally finished working on it after managing to fix it for older versions of IE, why microsoft cant just use webkit i dont know, would make it so much easier.

first off my div's on the page are like so

<div id='imagebox'>
<ul id='picFlickBox'>
<li><img id='contentimage' src='images/commercial_interiors_b1.jpg'></li>
<li><img id='contentimage' src='images/superyacht-hotel-interiors.jpg'></li>
<li><img id='contentimage' src='images/mainimage.jpg'></li>
<li><img id='contentimage' src='images/office%20interior.jpg'></li>
</ul>
</div>

with this css
#imagebox{
        height:300px;
        width:400px;
        overflow:hidden;
        background-color:#cecece;
        float:left;
        position:relative;
}
#imagebox ul{
        position:relative;
        left:0;
        top:0;
        width:3000px;
        height:300px;
        list-style-type:none;
}
#imagebox ul li{
        float:left;
        padding:0;
        width:400px;
        height:300px;
        overflow:hidden;
}
#imagebox ul li img{
        width:400px;
        height:300px;
}
#contentimage{
        border-style:solid;
        border-color:#545454;
        border-width:1px;
}
#picFlickBox{
        filter:alpha(opacity = 0);
        opacity:0;
}

once you got that its onto the javascript

var picTimer = 10;//how long pic stays on page(is equal to picTimer * how often picFlick is fired)
var picFlickCounter = picTimer;
var picI = 1;
var pics = 4;//number of pictures
document.getElementById('picFlickBox').FadeState = -2;//tell the fade function our image starts hidden
function picFlick(){
        var theBox = document.getElementById('picFlickBox');

        if(picFlickCounter == picTimer){
                switchPic();
                picFlickCounter = 0;
        }
        if(picFlickCounter == (picTimer-1) || picFlickCounter == 0){
                fade('picFlickBox');
        }
        picFlickCounter++;
}
function switchPic(){
        var theBox = document.getElementById('picFlickBox');
        leftPX = (picI*400) - 400;
        theBox.style.left = '-'+leftPX+'px';
        picI++;
        if(picI > pics){
                picI = 1;
        }
}
var TimeToFade = 1000.0;

function fade(eid){//fade from www.switchonthecode.com
        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){//animateFade from www.switchonthecode.com
        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);
}

t=setInterval("picFlick()", '1000');//fire picFlick every 1s

reply

Steve
04/26/2011 - 09:11

Great script. Thank you!

One issue I am having: in IE 7 & 8, the text in my DIV is coming out fuzzy. Perhaps it has something to do with this using filters, whereas the good browsers don't?

Have you ever seen or heard of this problem, and any idea how to fix it?

reply

Nate
05/10/2011 - 15:01

This is awesome! Thanks so much. This makes it so much easier for me.

reply

Anonymous
05/17/2011 - 20:17

Hi great code, i would just like it to fade in how do i modify the above code to make it only fade in.

Thanks

reply

Bim
05/23/2011 - 05:08

Hey,

yes it is a great bit of code, just editing it myself for a pic transition so wrote it to just fade in for you.

you just need to change the second function to this

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.opacity = '1';
                //element.style.filter = 'alpha(opacity = ' + (element.FadeState == 1 ? '100' : '0') + ')';
                element.style.filter = 'alpha(opacity = 100)';
                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);
}

just tells it to always fade in & always finish at 100% opacity you could set this to 80% or something different if needed

Bim

reply

Aurelien D
05/25/2011 - 13:21

You guys rock - thanks for sharing the knowledge!! :D :D :D

reply

Anonymous
06/17/2011 - 21:41

Could someone please tell me how to add a close button to this? I am using this script on a CSS lightbox and have so far had no luck.

Thanks in advance.

reply

Anonymous
07/11/2011 - 21:02

ur tutorial is very complicated. how about use toggle?

Exm:

<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>

</head>

<body>

<button>fadeToggle p1</button>
<button>fadeToggle p2</button>
<p>This paragraph has a slow, linear fade.</p>

<p>This paragraph has a fast animation.</p>


<div id="log"></div>

<script>
$("button:first").click(function() {
  $("p:first").fadeToggle("slow", "linear");
});
$("button:last").click(function () {
  $("p:last").fadeToggle("fast", function () {
    $("#log").append("<div>finished</div>");
  });
});
</script>


</body>

reply

Ldk
10/12/2011 - 17:43

You're stupid right ?

I mean, you can't be serious if you are comparing a jquery implementation with a full js implementation of fade (from scratch).

reply

Kpackama
07/26/2011 - 02:11

Thank you very much for the tutorial/explanation!

I've been trying to create one of those menus that are hidden outside of the screen and show just a little bit, and slide in when hovered. I've been having a tough time doing this, but with your time method it works just fine. My code is written in a clumsy way, so one shouldn't be scared of an occasional bug. Anyway, here's to see how useful this method can be:

var position = -2;
var fullTime = 2000;
var timeLeft = 0;
function showMenu() {
        if (position == -2) {
                position = 1;
                timeLeft = fullTime;
                setTimeout("moveMenu(" + new Date().getTime() + ")", 33);
        }
        if (position == -1) {
                position = 1;
                timeLeft = fullTime - timeLeft;
                setTimeout("moveMenu(" + new Date().getTime() + ")", 33);
        }
}
function hideMenu() {
        if (position == 2) {
                position = -1;
                timeLeft = fullTime;
                setTimeout("moveMenu(" + new Date().getTime() + ")", 33);
        }
        if (position == 1) {
                position = -1;
                timeLeft = fullTime - timeLeft;
                setTimeout("moveMenu(" + new Date().getTime() + ")", 33);
        }
}
function moveMenu(lastTick) {
        var curTick = new Date().getTime();
        var elapsedTicks = curTick - lastTick;
        var menu = document.getElementById('menu');
        if (timeLeft <= elapsedTicks) {
                if (position == 1) {
                        menu.setAttribute('style','left :'+(5)+'px; top: 60px;');
                        position = 2;
                }
                if (position == -1) {
                        menu.setAttribute('style','left :'+(-130)+'px; top: 60px;');
                        position = -2;
                }
                return;
        }
        timeLeft -= elapsedTicks;
        var value = timeLeft/fullTime*135;
        if (position == -1) value = -130 + value;
        if (position == 1) value = 5 - value;
        menu.setAttribute('style','left :'+value+'px; top: 60px;');
        setTimeout("moveMenu(" + new Date().getTime() + ")", 33);
}

I just set the showMenu() and hideMenu() functions in the onMouseOver and onMouseOut of the menu element.

Thanks again!

reply

Anonymous
08/11/2011 - 12:39

I used the example above and changed it to make one string of text disappear and another reappear when clicking on a button. This worked fine. But then I put a background image on the page and now when it fades in and out, it is choppy, there is no longer a smooth fade. Does anyone know why this should be so? Its not like I am reloading the background image with each fade which might cause an extra load on the system...

reply

Krishna Kumar
08/18/2011 - 14:45

really great work.....

reply

Shynn
09/05/2011 - 21:48

Hi there, have you ever try this in apex? =)

Thanks and Godspeed!
shynn

reply

Beasta.Inc
09/06/2011 - 07:27

Hi, just wanted to say thanks for the code. It's helped me out a lot and I only have one question. I'm new to Js and Html (self taught for the past 18 months) and I'm wondering is it possible to make it so it doesn't fade out completely. Say I wanted it to stop so it's only around 30 or 40 percent transparent, do I tell it that once it reaches a predefined value to stop or am I way off the mark???

Cheers for your help (& the code).

reply

Anonymous
09/11/2011 - 07:15

Guys with this code how can you just make it juast fade in and not fade out I mean the ID just keeps fading in when clicked ...

reply

Anonymous
09/12/2011 - 01:48

I would like to set a timeout that every 5 seconds a new image will fadein, when this image fadesout the same time a fadein will occur with the next image, is this possible??

reply

Thaius
10/24/2011 - 17:51

Great script, solved all my problems, many thanks!

reply

Anonymous
10/31/2011 - 01:19

May I ask the whole code? :)

reply

Immabed
11/08/2011 - 13:14

Really Impressive stuff. It took me awhil to understand as I have only begun to learn javascript about two weeks ago, but I have managed to pull alot out of this and am using it to create an image fader that is time based.

reply

Immabed
11/15/2011 - 13:43

Sorry for the big post, but I'm having problems with this code that I based, loosely, off the ideas in this tutorial. It is supposed to be an image fader, that fades an image out, then fades the next one in. It doesn't seem to do anything, even though i have tried activating it in many ways.

var FadeTime = 500

        function imgchanger()
        {
                var numOfFiles = 5
                var pic = Math.floor(Math.random()*numOfFiles);
                var picfile = "<img class=\"form\" id=\"changingpic"+pic+"\" src=\"images/Commercial/BCP_Local00"+pic+".jpg\" />"
                document.getElementById("picchanger").innerHTML = picfile
                var element.FadeTimeLeft = 0
                var t=setTimeout("imgfader(0," + pic + "," + new Date().getTime() + ")",25)
        }

        function imgfader(flip,eid,lastTick)  //flip=0 if fading in, flip=1 if fading out
        {
                var curTick = new Date().getTime()
                var elapsedTicks = curTick - lastTick
                var element = document.getElementById("changingpic"+eid)
                element.Fade = flip
                if(element.Fade == 1) //Fading in
                        {
                        element.FadeTimeLeft = element.FadeTimeLeft - elapsedTicks     
                        element.style.opacity = element.FadeTimeLeft/FadeTime
                        }
                else if(element.Fade == 0) //Fading out
                        {
                        element.FadeTimeLeft = element.FadeTimeLeft + elapsedTicks
                        element.style.opacity = element.FadeTimeLeft/FadeTime
                        }
                if(element.style.opacity = 0)  //finished fading out, start again.
                        {
                        var t=setTimeout("imgchanger()",0)
                        }
                else if(element.style.opacity = 1)  //finished fading in, set timer until fade out
                        {
                        var t=setTimeout("imgtimer(" + eid + ")",5000)
                        }
                else  //fading in or out currently, continue fading
                        {
                        var t=setTimeout("imgfader(" + flip + "," + eid + "," + new Date().getTime() + ")",25)
                        {
        }

        function imgtimer(eid)
        {
        var t=setTimeout("imgfader(1," + eid + "," + new Date().getTime() + ")",25)
        }      

reply

Adriana
01/03/2012 - 17:31

Thanks a lot! works perfectly!!

reply

FaceOff
01/17/2012 - 10:25

Hi.

I implemented this code to my page.
I have some buttons such as "contact" "about us" etc. which I used this fade javascript on to make information appear fading up when I click on one of the buttons.

!
My question is...

is there a way to make a automatic fade-out when I click another button...?

reply

bastian
03/09/2012 - 08:49

hellp thx for the nice code but i try to get the reverse state, that its starts hidden and if u press on the button it appears.

the code i found in the comments doesn´t work :/

have somebody an idea?

reply

Glen
04/05/2012 - 13:02

Thanks for this very useful and powerful tutorial. I would just like to add one thing I came across while modifying this code. I was trying to wrap the whole script in an anonymous function so I could have multiple objects fading on the page without the variables interfering with each other. When I did this, I was getting errors about undefined functions within setTimeout(). Here is an example of the original:

setTimeout("animateFade(" + curTick + ",'" + eid + "')", 33);

And here was my solution:
setTimeout(function(){animateFade(cur_tick,e_id);}, 33);

The issue was passing the animateFade function as a string to setTimeout. If setTimeout gets a string, it attempts to evaluate, instead of referencing the actual function. Why it works before wrapping this entire script in an anonymous function I'm not sure (perhaps something to do with function scope), but I thought I would pass along my fix if anyone else was running into this.

See this thread for more info:

http://stackoverflow.com/questions/1101668/how-to-use-settimeout-to-invoke-object-itself

reply

Anonymous
04/22/2012 - 07:04

This is just what I'm after - thanks!, just one thing though.. rather than a button, I'm trying to use expand and collapse images that replace each other when the text is displayed/hidden. Anyone any idea how to change the script to do that?

reply

rashid
04/26/2012 - 08:10

any reason you might be using this in 2012 instead of jquery, mootools, prototype and God knows what all ?

reply

Anonymous
05/14/2012 - 11:59

You learn more if you do it yourself, and you are more able to edit it to have exactly the behavior you want if you are using the effect within a larger script.

reply

Add Comment

Put code snippets inside language tags:
[language] [/language]

Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]

See here for supported languages.

Javascript must be enabled to submit anonymous comments - or you can login.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.