Categories
Other Programming

Javascript + CSS Fade In

Edit:  This was created before I had discovered JQuery or MooTools.  Please, for the love of God, use those instead.

You’re working on your first sweet ajax form implementation.  You’ve got the form communicating asynchronously with the server and sending status updates between to the two.  However, when you want to let users know that the form is processing, the processing image just kind of “pops” in there.  What you need is an easy “fade in implementation”.

The HTML

<div id=”myimage”>
<img src=”myimage.gif” />
</div>

The CSS

#myimage {
opacity: 0;
}

The Javascript

function fadeIn(id, level) {
if(document.getElementById) {
object = document.getElementById(id);
if(level <= 100) {
setOpacity(object, level);
level += 10;
window.setTimeout(“fadeIn(‘”+id+”‘,”+level”)”, 100);
}
}
}

function setOpacity(object, level) {
level = (level == 100)?99.999:level;
object.style.filter = “alpha(opacity:”+level+”)”;
object.style.KHTMLOpacity = level/100;
object.style.MozOpacity = level/100;
object.style.opacity = level/100;
}

How To Use It
Using this code is pretty easy.  Make sure that the CSS & Javascript are included in your document correctly, then do the following.

fadeIn(“myimage”,0);

If you have any questions, leave a comment and I’d be glad to help.

By Jack Slingerland

Founder of Kernl.us. Working and living in Raleigh, NC. I manage a team of software engineers and work in Python, Django, TypeScript, Node.js, React+Redux, Angular, and PHP. I enjoy hanging out with my wife and son, lifting weights, and advancing Kernl.us in my free time.