Search code examples
javascripthtmlcssslideshow

How can I fix seeing all of my slideshow images on page loading?


I'm using this code to run my slideshow (see snippet). However, when I load my page, I quickly see all of the slides since the script doesn't work instantly. To fix it, I think I'll have to hide them using css, I just don't know how. I've used something like this before in another slideshow, this worked out there:

#slideshow > div ~ div{
   display: none;
}

var myIndex = 0;
carousel();

function carousel() {
	var i;
	var x = document.getElementsByClassName("mySlides");
	for (i = 0; i < x.length; i++) {
	   x[i].style.display = "none";  
	}
	myIndex++;
	if (myIndex > x.length) {myIndex = 1}    
	x[myIndex-1].style.display = "block";  
	setTimeout(carousel, 5000); 
}
	.slideshow{
		margin-top: 15px;
		z-index: 10;
	}
	
	.slide{
		width: 100%;
	}
<div id="slideshow" name="slideshow" class="slideshow">
		 <img src='{ROOT}img/Camerashop24/slide1.jpg' alt="slide-1" class="slide mySlides">
		 <img src='{ROOT}img/Camerashop24/slide2.jpg' alt="slide-2" class="slide mySlides">
		  <img src='{ROOT}img/Camerashop24/slide3.jpg' alt="slide-3" class="slide mySlides">
			<img src='{ROOT}img/Camerashop24/slide4.jpg' alt="slide-4" class="slide mySlides">
	</div>

So, how do I adjust it so that it works again?


Solution

  • When your page loads its better only first image is visible.

    .slideshow img:not(:first-child) {
        display: none;
    }
    

    This hides all images but the first one. If it has problem in some browsers, use this:

    .slideshow img{
      display: none;
    }
    
    .slideshow img:first-child{
      display: block;
    }