I am working on a little javascript gallery that displays a number of differenty images, and fades in and out. Unfortunately I can't seem to get the fade in properly working.
Can anybody tell me how to fix this? This is my code so far:
//This goes in the head of the html file:
<script type="text/javascript">
var imageCount = 4;
var image = new Array(imageCount);
image [1] = "slideshow/testimg1.jpg"
image [2] = "slideshow/testimg2.jpg"
image [3] = "slideshow/testimg1.jpg"
image [4] = "slideshow/testimg2.jpg"
</script>
//This goes in the body of the html file
<img width="760" height="260" name="slide">
<script type="text/javascript">
var step = 1;
document.images.slide.style.opacity = 1;
function NextImage()
{
//Change image
document.images.slide.src = image [step];
//Change step
if (step < imageCount)
step++;
else
step = 1;
FadeIn();
}
function FadeIn()
{
if (document.images.slide.style.opacity < 1)
{
//Increase opacity
document.images.slide.style.opacity += 0.05;
setTimeout("FadeIn()", 20);
}
else
{
//Set opacity to 1, fade out
document.images.slide.style.opacity = 1;
setTimeout("FadeOut()", 4000);
}
}
function FadeOut()
{
if (document.images.slide.style.opacity > 0.05)
{
//Reduce opacity
document.images.slide.style.opacity -= 0.05;
setTimeout("FadeOut()", 20);
}
else
{
//Set opacity to 0.5, change the image
document.images.slide.style.opacity = 0.05;
NextImage();
}
}
NextImage();
</script>
The idea is that is swithes between the NextImage, FadeIn and FadeOut functions. I have everything working except for the fades, because it whenever I test it it goes like this:
Load image, fade out, load second image, freeze.
I hope someone can help me with this. Thanks in advance.
~Luca.
EDIT: This fixed it:
//Increase opacity
var x = parseFloat(document.images.slide.style.opacity) + 0.05;
document.images.slide.style.opacity = x;
setTimeout(FadeIn, 20);
Thanks!
Change:
setTimeout("FadeIn()", 20);
to
setTimeout(FadeIn, 20);
and see if that helps (and the other setTimeout functions as well).
EDIT/Addition: The document.images.slide.style.opacity += 0.05; is not actually incrementing. Try the following modification:
//Increase opacity
var x = parseFloat(document.images.slide.style.opacity);
x += 0.05;
document.images.slide.style.opacity = x;
setTimeout(FadeIn, 20);