0

I'm trying to display images from a folder, But when the image does not exist. I want it to skip to the next one. I'm using 'display none' here. Below is the code. Thanks in Advance. Sorry if there's any mistake.

<div class="w3-content w3-section" style="position:fixed; height: 100%; width:100%;">
<img class="mySlides" src="uploads/1.JPG" align="middle" >
<img class="mySlides" src="uploads/2.JPG" align="middle">
<img class="mySlides" src="uploads/3.JPG" align="middle">
<img class="mySlides" src="uploads/4.JPG" align="middle">
</div>

<script>

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";  //For Eg if 1.JPG is not found it displays black screen for 5secs.
  setTimeout(carousel, 5000); // Change image every 5 seconds

 }
</script>
  • https://stackoverflow.com/questions/18837735/check-if-image-exists-on-server-using-javascript – Matey Jan 08 '18 at 15:01

1 Answers1

0

Add attribute onerror in every img tag

<div class="w3-content w3-section" style="position:fixed; height: 100%; width:100%;">
<img class="mySlides" src="uploads/1.JPG" onerror="this.remove()" align="middle" >
<img class="mySlides" src="uploads/2.JPG" onerror="this.remove()" align="middle">
<img class="mySlides" src="uploads/3.JPG" onerror="this.remove()" align="middle">
<img class="mySlides" src="uploads/4.JPG" onerror="this.remove()" align="middle">
</div>

Hope it'll help you out.

Pradeep Rajput
  • 724
  • 7
  • 11