faqts : Computers : Programming : Languages : JavaScript : Images

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

22 of 26 people (85%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How can I fade images in and out?

Jan 19th, 2001 13:46
Martin Honnen,


As explained in 
  http://www.faqts.com/knowledge_base/view.phtml/aid/6692/fid/128
you can change the opacity/transparency of a page element in NN6 and 
IE5+. By doing that incrementally you can fade an image in or out. Here 
is example code with two images faded in and one faded out:
<HTML>
<HEAD>
<SCRIPT>
var step = 10;
var delay = 100;
function fadeImageIn (img) {
  if (document.all || navigator.appName == 'Netscape' && parseFloat
(navigator.appVersion) >= 5) {
    img.opacity = 0;
    setOpacity(img.name);
  }
}
function fadeImageOut (img) {
  if (document.all || navigator.appName == 'Netscape' && parseFloat
(navigator.appVersion) >= 5) {
    img.opacity = 100;
    setOpacity(img.name, -step);
  }
}
function setOpacity (imgName, step, delay) {
  if (!step)
    step = window.step;
  if (!delay)
    delay = window.delay;
  var img = document.images[imgName];
  img.opacity += step;
  if (document.all)
    img.style.filter = 'alpha(opacity = ' + img.opacity + ')';
  else if (navigator.appName == 'Netscape' &&
parseFloat(navigator.appVersion) >= 5)
    img.style.MozOpacity = img.opacity + '%';
  if (step > 0 && img.opacity < 100 || step < 0 && img.opacity > 0)
    setTimeout('setOpacity("' + img.name + '",' + step + ', ' + delay 
+ ')', delay);
} 
</SCRIPT>
</HEAD>
<BODY>
<IMG NAME="imageName"
     SRC="kiboInside.gif"
     STYLE="filter: alpha(opacity=0); -moz-opacity: 0%"
     ONLOAD="fadeImageIn (this)"
>
<IMG NAME="buttonOn"
     SRC="buttonOn.gif"
     STYLE="filter: alpha(opacity=0); -moz-opacity: 0%"
     ONLOAD="fadeImageIn (this)"
>
<IMG NAME="buttonOff"
     SRC="buttonOff.gif"
     STYLE="filter: alpha(opacity=100); -moz-opacity: 99%"
     ONLOAD="fadeImageOut (this)"
>
</BODY>
</HTML>
Note that NN6 currently has a bug that is why the initial opacity of 
the third image is set to 99% and not 100%.