CancelImage Upload

How to produce a slow image fade-in effect with JavaScript

Previously I have discussed how the CSS Opacity property can be accessed via JavaScript, and how it can be used to fade an image on mouseover. This page then will discuss how a slow image fade-in effect can be achieved by adding a bit more code to the standard opacity changing JavaScript functions.

The key here is to change the opacity one point at a time, while making use of JavaScript's time delay function:

var opacity = 0;

function initiate()
{

       opacity++;

       setInterval("fadein()", 500);

}

initiate();

As you can see after the time delay the function fadein() will be called upon, which will do just as the name says:

function fadein()
{

       var fadeImg = document.getElementById('fadeImg');

       var browserName=navigator.appName;

       if(browserName=="Microsoft Internet Explorer")
       {

              browserOpacity = opacity / 10;

              fadeImg.filters.alpha.opacity = browserOpacity;

       }
       else
       {

              browserOpacity = opacity / 1000;

              fadeImg.style.opacity = browserOpacity;

       }

       if(opacity < 1000)
       {

              initiate();

       }

}

What happens inside this function is pretty straightforward. First we check if the browser being used is Internet Explorer, and feed it the appropriate opacity changing function accordingly. Then if the opacity is still below 100% we re-call the function initiate().

Here is the JavaScript code inside a HTML Document:

<html>
<head>
<script type = "text/javascript">

var opacity = 0;

function fadein()
{

       var fadeImg = document.getElementById('fadeImg');

       var browserName=navigator.appName;

       if(browserName=="Microsoft Internet Explorer")
       {

              browserOpacity = opacity / 10;

              fadeImg.filters.alpha.opacity = browserOpacity;

       }
       else
       {

              browserOpacity = opacity / 1000;

              fadeImg.style.opacity = browserOpacity;

       }

       if(opacity < 1000)
       {

              initiate();

       }

}


function initiate()
{

       opacity++;

       setInterval("fadein()", 500);

}

initiate();

</script>
</head>
<body>
<img id="fadeImg" src="images/image.jpg" style="opacity:0.0; filter:alpha(opacity=0)"/>
</body>
</html>


Login
Want to leave a comment?

No problem. Just enter your email and password below.


register | home | reminder

myDesignTool Networking • www.mydesigntool.cominfo@mydesigntool.com