I am setting up a Bootstrap carousel. I wrote the HTML for 20 images, and the number of images changes weekly. The image names are Pic001, Pic002, etc. How do I hide the image’s parent div that has an error? (no image to be found, for that HTML)
$(document).ready(function() {
$("img").each(function() {
var $this = $(this);
this.onerror = function() {
$(this).parent().hide();
};
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="carousel-item" id="Slide010">Hide this
<img class="d-block w-100" src="/sites/Yo/Flyers/Pic010.jpg" alt="Slide10" />
</div>
2
Answers
You are too late when you execute the code. All load or error event handlers on the images have already run.
Instead have a dummy image (blank or such) Use a data attribute, load the image from the data attribute which then can trigger the error
Alternatively preload the images and create the carousel from the list of images that worked
Your approach with
this.onerror
is on the right track! However, you don’t need to loop over allimg
elements if you’re already dynamically handling errors as they occur. try this option, that ensures the parent.carousel-item
div is hidden if the image fails to load:Because I would have done the same.