Ever visit a website and see some elements which seem to disappear or appear with a gradual fade in or fade out effect? Ever wonder how that is done? I am sure you have at one point. You probably dug around Google and would find some long winded scripts that may or may not work quite right. Maybe they are hard to setup and always had bugs. We here at DIC hear your pain. So I have taken the liberty of putting together a small little well written example to show you how to do it and allow you to just plug it into your project and get some fading. Check it out, right here on the Programmer’s Underground!
The idea of fading isn’t an overly complicated one if you know where to look and remember to take into account the differences between the browsers. To control a fade for an object you must do a few things…
1) Get a reference to that item on the page. This is typically done using the document.getElementById(“nameofobjectid”); function call. Give an object, like a div table or image, an id tag and use this method to actually refer to it. It is advised that you put your javascript at the top of the file for this so that by the time the page is fully loaded, your javascript can find the object.
2) Use Cascading StyleSheets (CSS) attributes for “opacity” (Mozilla) and “filter” (IE) to control the level of transparency for the given object.
3) Use the setTimeout() and clearTimeout() to control the rate at which the fade effect happens. These functions setup a timer in which you can call a method after a set period of time or clear a currently running timer. You will use these to call the fade functions every so many seconds or cancel a fade effect from continuing.
Those are the three main parts you need for getting this little trick to work. The example I am about to show below was setup for example purposes, but I know for a fact that it works on DIV elements, Tables, and Images. Other elements have yet to be tried out. I used this method to create a floating bubble description box for records I was displaying on a website. I would highlight a link and show the bubble, then when I moved my mouse away (onmouseout) I would hide the bubble using a nice fade out effect.
Lets dive into the code!
<script type="text/javascript"> // Some global vars for the timer, to hold a reference to our object, and our visibility toggle value. var timerid; var obj; var visible = true; // Toggles the fade effect on and off. function toggleFade(objectName) { // Get reference to target object obj = document.getElementById(objectName); if (obj) { // Clear any timers currently running for fades. clearTimeout(timerid); // If we are visible, hide it otherwise show it. if (visible) { hideFade(100); visible = false; } else { showFade(0); visible = true; } } } // Function for hiding our object with outgoing fade function hideFade(opac) { if (obj) { // If opacity is greater than 0, decrement opacity setting by 10 every 50 milliseconds. if (opac > 0) { obj.style.opacity = (opac / 100); obj.style.filter = "alpha(opacity=" + opac + ")"; timerid = setTimeout("hideFade(" + (opac - 10) + ")",50); } else { // Opacity is zero, so hide it and then set its opacity back to full. obj.style.visibility = "hidden"; obj.style.opacity = 1; obj.style.filter = "alpha(opacity=100)"; // Clear the timer that is triggering the fade to stop it. clearTimeout(timerid); } } } // Function for showing the element with incoming fade function showFade(opac) { if (obj) { // If opacity is less than 100, make it visible and then increment its opacity. if (opac < 100) { obj.style.visibility = "visible"; obj.style.opacity = (opac / 100); obj.style.filter = "alpha(opacity=" + opac + ")"; timerid = setTimeout("showFade(" + (opac + 10) + ")",50); } else { // Opacity is 100, so make sure it is at full opacity. obj.style.opacity = 1; obj.style.filter = "alpha(opacity=100)"; // Clear the timer that is triggering the fade to stop it. clearTimeout(timerid); } } } </script>
The script above includes in-code comments to show you how to setup the different pieces. Basically I have setup a controlling function called “toggleFade()” which takes the name of the object I want to fade and either calls the hide or show function. So for instance if I was to put it on a button I could call it using something like this…
<input type="button" value="Fade" onclick="toggleFade('myobject')"/>
When I click the button it calls our toggleFade function and determines if the element (specified in the parameter) needs to be faded in or out. We do this by getting the reference to our object using the name we passed to the function. In our example call above, the name of the object was “myobject” which was connected to a DIV tag. Once we determine if the item should be faded in or out, we call the appropriate method showFade or hideFade and pass it the starting opacity value. However, we will do this after we have stopped any timers that had been running previously using clearTimeout.
In each of these two functions we determine if the object reference is set and then set the opacity using both the opacity and filter CSS properties so that we can make sure it works in both FireFox and IE. We then start a timer where we call the function again (recursively), passing it the next opacity value -10 or +10 in value. So the method essentially makes several calls every 50 milliseconds.
So as these functions progress they are being called with a value that approaches 0 for the hiding effect and 100 for the show effect. Once these two functions either reach 0 or 100, we then reset the opacity back to standard. If it is the hide function we also hide the element for extra safety. We also set it to visible in the show function for extra safety as well. Lastly we clear the timer that controls the fade.
As you can see the show and hide functions are very similar and probably could be melted down even further into one function. I wanted to show you them in distinct functions so you can see the process or perhaps use one or the other if you don’t want both. I would advise that you take these functions and put them into a file on their own and link the file to any page you want to use them. If you put them in a file like “fade.js” you could just link it to a page like so…
<html> <head> <title>My Fade Object Page</title> <script type="text/javascript" src="fade.js"></script> </head> ...
You can see above we have defined a script tag in the heading tags of our page which would link to our functions. Then you can call toggleFade(“nameofobject”) anytime you want to fade an object.
Keep in mind though that this is designed as an example and if you wish to fade a bunch of objects on a page, you may need to customize the global variables at the top of the page to keep track of each object’s timers and toggle value. You could put these values into an array perhaps and essentially loop through objects you want to fade or juggle around the objects in different data structures as you like. This code is highly modifiable and easy to extend.
Feel free to use this code as you see fit, just don’t claim it as your own or slap on your own copyright.
I hope you find this code useful to you and that you create some wickedly neat fade effects with it. Thanks for reading! 🙂