0

I have multiple images in a single div and I want to take some action only when all images in this div are loaded, which sounds simple but I was unable to find any neat solution to do this.

<div class="imgs">
  <img src="img1.jpg">
  <img src="img2.jpg">
  <img src="img3.jpg">
</div>

I found Official way to ask jQuery wait for all images to load before executing something which suggests to use $(window).on("load", function(){}), but I have multiple div and I want to take action as long as all images in each div are loaded, not when all images in the DOM are loaded.

I also found some JavaScript way to do it, such as jQuery or Javascript check if image loaded and How to make Javascript wait for all images to load before proceeding?, which are quite complicated for such an seemingly easy task.

6
  • 3
    In the Javascript question that you link to, there is an answer with 3 upvotes, it has a solution that is about 3 lines long. Your not going to find a solution much simpler than that one. Commented May 25 at 2:26
  • Can you kindly point to me which is the solution? I only see one 3 upvotes and the solution is at least 20 lines.
    – SamTest
    Commented May 25 at 14:02
  • 1
    That is the one: stackoverflow.com/a/75570052/20901722 If you use his "minimalist form", remove the comments and log statements, you get down to 3 or 4 lines of code. The exact number of lines is not important here, it's the fact that it's a simple solution. Good luck. Commented May 25 at 17:25
  • Thanks! This does not seem solve my problem, as I said, I have multiple <div> that contain images, which are initially hidden, and I want to display individual <div> as long as images in that <div> are all loaded. The solution delt with ALL images in the DOM.
    – SamTest
    Commented May 25 at 20:32
  • Totally not true. The solution starts out with .... const images = [...document.querySelectorAll("div img")] Commented May 25 at 21:22

1 Answer 1

0

How about using a simple counter for this purpose?

jQuery(document).ready(function($) {
  const imgs = $('.imgs .img');
  let loadCounter = 0;

  imgs.on('load', function() {
    loadCounter += 1;

    if (loadCounter === imgs.length) {
      console.log('every img loaded');
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<div class="imgs">
  <img class="img" src="https://picsum.photos/id/237/200/300" />
  <img class="img" src="https://picsum.photos/id/238/200/300" />
  <img class="img" src="https://picsum.photos/id/239/200/300" />
</div>

1
  • I thought about doing it this way. But I am not sure how exactly "on" works. Do "on" for an array happens sequentially or concurrently? If the 2nd image has already been loaded when the "on" event checks it, will the on("load", ...) still trigger the function to run?
    – SamTest
    Commented May 27 at 17:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.