JavaScript Image Fader
Introduction
This code allows you to set up easy fading in and out of images on a web page. It is a common thing now to see columns of latest images on the sides of website pages. However, there is no code anywhere for actually doing the fading of images. So, in this article, that is what I present: some simple JavaScript code that can be incorporated into any website to fade images in and out.
Using the Code
The code can be used very simply. Add the provided JS file in the head like any other script. Put an onload
event in the body
tag that calls the method FadeAllImages()
. Then, in the JS file provided, find the FadeAllImages
method which should look like:
function FadeAllImages()
{
FadeImage('Image1', 0, 0);
FadeImage('Image2', 5500, 1);
FadeImage('Image3', 11000, 2);
FadeImage('Image4', 16500, 3);
}
Simply add, remove, or change the calls to FadeImage
to fade different images. The three arguments are: ID of the image to fade, Delay before starting the first fade, and the file number in the file list which the image tag is set to initially. The file list is defined at the start of the JS file along with a number of other useful variables. They are:
var MaxOpacity = 1.0;
var MinOpacity = 0.0;
var ChangeTotalTime = 10000;
var ChangePeriod = 20;
var DisplayTime = 2000;
var HideTime = 0;
var Times = [];
var FileNames = new Array();
FileNames[0] = "Images/Backgrounds/Carribean-Beach.jpg";
FileNames[1] = "Images/Backgrounds/Red-Dream-Swirls.jpg";
FileNames[2] = "Images/Backgrounds/Space.jpg";
FileNames[3] = "Images/Backgrounds/Swirls-Of-Fire.jpg";
FileNames[4] = "Images/Backgrounds/Purple-Starry-Hearts.jpg";
FileNames[5] = "Images/Backgrounds/Blue-Cells.jpg";
FileNames[6] = "Images/Backgrounds/Blue-Cells-2.jpg";
FileNames[7] = "Images/Backgrounds/water-008.jpg";
MaxOpacity
is the maximum opacity level you wish to fade to. This has to be within 0 and 1, with maximum two decimal places.MinOpacity
is the minimum opacity level you wish to fade to. This has to be within 0 and 1, with maximum two decimal places. It must also be less thanMaxOpacity
.ChangeTotalTime
is the length of time taken to fade out or in in milliseconds. I have it set to 10,000, a reasonable 10 second fade which looks good if you have a column of fading images.ChangePeriod
is how frequently the code updates the image's fade level. I have it set to 20 milliseconds, which is fine in most cases. At about 100 milliseconds, your eye starts to see jerkiness in the fade.DisplayTime
is the length of time between the image faded in being fully opaque and the next fade out starting (in milliseconds).HideTime
is the length of time between the image faded in being fully transparent and the next fade in starting (in milliseconds).Times
is a variable used to keep the fades correct as thesetTimeout
function in JavaScript is not accurate.FileNames
is the files list. It is the list of all the image files you wish to display. When an image is fully faded out, a random new image is chosen from the list. Currently, my code supports a maximum list size of 1000 - limited by theRandom
function used in my code, but more than enough for most people's uses I expect.
The Fade Functions
The fade functions are very similar though the madly more interesting is FadeOut
. The code looks like:
function FadeOutImage(OpacityLevel, Tag, FileNum)
{
try
{
var now = new Date();
var StartTime = Times[Tag];
var Gradient = (MaxOpacity - MinOpacity) / ChangeTotalTime;
var TimePassed = now - StartTime;
var Value = Gradient * TimePassed;
Value = (MaxOpacity - MinOpacity) - Value;
OpacityLevel = Value > MinOpacity ? Value : MinOpacity;
OpacityLevel = roundNumber(OpacityLevel, 2);
document.getElementById(Tag).style.opacity = OpacityLevel;
document.getElementById(Tag).style.filter =
"alpha(opacity=" + (OpacityLevel * 100) + ")";
document.getElementById(Tag).style.MozOpacity = OpacityLevel;
if(OpacityLevel > MinOpacity)
{
setTimeout("FadeOutImage(" + OpacityLevel + ", '" +
Tag + "', " + FileNum + ")", ChangePeriod);
}
else
{
FileNum = Random(FileNames.length);
document.getElementById(Tag).src = FileNames[FileNum];
var CommandString = "Times['" + Tag + "'] = new Date();";
setTimeout(CommandString, HideTime);
setTimeout("FadeInImage(" + OpacityLevel + ", '" +
Tag + "', " + FileNum + ")", HideTime);
}
}
catch(e)
{
}
}
To make sure I could use the same method for any image without having external variables (excluding Times
), the variables for an image are passed through arguments. These include: the current fade level (OpacityLevel
), the ID of the image to fade (Tag
), and the current file being shown (FileNum
). The method first works out what the gradient of the fade should be. As this is a linear fade, it is a straight line graph and so can be worked out by the simple equation: change in y over change in x --> Overall change in opacity / Total time for fade --> (MaxOpacity - MinOpacity) / ChangeTotalTime
. It then works out the TimePassed
since the beginning of the fade, and thus what the current value should be, using Gradient * TimePassed
. As this is a fade out, the value is actually the reverse, which is simply worked out by Overall Change - Value
. As there can be floating point errors in JavaScript, the value is checked against MinOpacity
(what we are fading to) and then rounded to two decimal places. The opacity level is then set. To comply with the five main browsers (latest versions), style.opacity
and style.filter
are both set. style.opacity
takes a decimal value while style.filter
takes a value from 0 to 100. To allow some compatibility with older versions of FF that supported opacity, style.MozOpacity
is also set.
Finally, the code checks to see if we have completed the fade; if not, it sets a timeout with the change period to call itself and then continues. If the fade is complete, it picks a new random image (note: one improvement here could be not being able to pick the same file number as was already being shown), and then sets that as the image displayed. As the opacity is currently at 0 (by assumption from my example), the change in image is undetectable though it should be noted that if the new image is a different size, then that change will be seen if it affects the container or the surrounding element sizes and positions. The fade in method does much the same thing, but fades the image in and does not change the image when it is complete. The code loops between these two methods continually, thus creating a fade in, fade out effect, with the image that fades in changing each time. This is great for random image or latest images columns or any form of fading of images.
Points of Interest
Some points of interest are: the setTimeout
function is not accurate; the floats get progressively worse floating point errors, and IE JavaScript runs significantly slower than that of the four other main browsers (thus creating greater need for the Times
variable).
发表评论
oWMwHU Thank you for your article.Much thanks again.
sJ9goT I appreciate you sharing this blog article.Thanks Again. Really Great.