In the attached HTML code that I’ve found on the web to display pictures one-at-a-time every 5 sec with a fade-in/fade-out effect.
The only issue is that at the very beginning all pictures are shown at once and only after the first cycle is completed it performs as expected.
Can anybody advise how to modify the code such that it performs as expected since the beginning?
Thanks.
INDEX.HTML
----------
<!DOCTYPE html>
<html>
<head>
<!-- Comment -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="image-container">
<img src="image1.jpg" style="max-width: 100%; max-height: 100%;" alt="Image 1">
<img src="image2.jpg" style="max-width: 100%; max-height: 100%;" alt="Image 2">
<img src="image3.jpg" style="max-width: 100%; max-height: 100%;" alt="Image 3">
</div>
<script src="script.js"></script>
</body>
</html>
SCRIPT.JS
---------
/* Slide show - Start */
var images = document.getElementById("image-container").children;
var index = 0;
function fadeImages() {
var nextIndex = (index + 1) % images.length;
var currentImage = images[index];
var nextImage = images[nextIndex];
currentImage.style.opacity = 1;
var opacity = 0;
var interval = setInterval(function() {
opacity += 0.05;
nextImage.style.opacity = opacity;
currentImage.style.opacity = 1 - opacity;
if (opacity >= 1) {
clearInterval(interval);
currentImage.style.display = "none";
nextImage.style.display = "block";
index = nextIndex;
setTimeout(fadeImages, 5000);
}
}, 50);
}
fadeImages();
/* Slide show - END */
STYLE.CSS
/* Slide show CSS - Start */
#image-container img {
<!-- position absolute; -->
opacity 0;
transition opacity 1s ease-in-out;
}
#image-container imgfirst-child {
opacity 1;
}
/* Slide show CSS - END */
3
Answers
Have all images apart from the first be hidden:
Let’s first spot some issues:
style
attribute should be avoided for the rare cases when it’s really necessary or logic:
all over the placeimgfirst-child
is not a valid selector.is-active
in order to set the styles for the visible image/slideclearInterval
to allow users to pause the slideshow to enjoy the slide they’re hoveringLet’s start with removing IDs and using classes instead. Now you can have even multiple
Let’s hide all images and use that
.is-active
styles.Remember that if you have
position: absolute;
children, a parent is better defined also with aposition
other thanstatic
. We’ll userelative
:Now for the JavaScript part.
Since we have multiple sliders in one page, you could either create a
Class
, instantiate it passing a desired container ID or simply pass the container Element to yourfadeImages(elParent)
function.See how cleaner and simpler the JS is now:
and every slideshow (carousel) runs independently from each other.
Just tried simplify this task, maybe will be usefull
*thx roko-c-buljan for cats source