skip to Main Content

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


  1. 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

    $(function() {
      $("img").each(function() {
        this.onerror = function() {
          $(this).closest('.carousel-item').hide();
        };
        this.src = this.dataset.src;
      });
    });
    <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="dummy.gif" data-src="/sites/Yo/Flyers/Pic010.jpg" alt="Slide10" />
    </div>

    Alternatively preload the images and create the carousel from the list of images that worked

    Login or Signup to reply.
  2. Your approach with this.onerror is on the right track! However, you don’t need to loop over all img 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:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script>
      $(document).ready(function () {
        $("img").on("error", function () {
          $(this).closest(".carousel-item").hide(); // Hide the parent div with the .carousel-item class
        });
      });
    </script>
    
    <div class="carousel-item" id="Slide010">
      Hide this
      <img class="d-block w-100" src="/sites/Yo/Flyers/Pic010.jpg" alt="Slide10" />
    </div>
    

    Because I would have done the same.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search