Lightbox with Fade In Effect
Starting from the previous tutorial where images are loaded dynamically by Ajax, and with the addition of a JavaScript fade in function, we make the box appear gradually.
The code for the fade in effect
No change in the CSS descriptors is required, but the JavaScript code to display the box is complemented by two functions.
The gradient function:
function gradient(id, level)
{
var box = document.getElementById(id);
box.style.opacity = level;
box.style.MozOpacity = level;
box.style.KhtmlOpacity = level;
box.style.filter = "alpha(opacity=" + level * 100 + ")";
box.style.display="block";
return;
}
This function changes the opacity of a DOM element, in this case the <div> which contains the lightbox, and we take into account the various browsers for more compatibility.
The level 0 assigned to the level variable, makes transparent the element, and that varies up to 1 which is the total opacity, so is created the fade in effect.
The fade in function:
function fadein(id)
{
var level = 0;
while(level <= 1)
{
setTimeout( "gradient('" + id + "'," + level + ")", (level* 1000) + 10);
level += 0.01;
}
}
It creates the effect by calling the previous gradient function with incremented values.
The level of transparency decreases of 0.01 to each call, it is also used to calculate the delay that tends to grow.
An argument has been added to the openbox function:
openbox('images/acores.jpg', 1);
A value 1 enables the fade in effect, if the value is 0 or the parameter missing, the box is displayed directly.
Demonstration
All the files are included in the archive.
Download
- Lightbox with fade effect. Archive containing the script and the demo.