1

jquery/javascript: when to get the correct container div size?

<div>
<div class="container">
    <div class="slider">
        <img src="image1.jpg">
        <img src="image2.jpg">
    </div>
<div>
</div>

|container----|
--------------Slider--------
|image1       |  image2    | 
-----------------------------

What is the right time to get container width and set the image width to the container width?

Tried

   $(document).ready(function() {
      var width = $(".container").width();
      $("img").css("width", width + "px");
   });

The width is different every time the page is reloaded, e.g., 524, 1449, 1920

the correct value is 524.

When debugging the code, always get correct value 524. The reason might be that the container div is fully rendered during debugging mode (stopped at breakpoint).

eastwater
  • 4,624
  • 9
  • 49
  • 118
  • 1
    How are you setting the container width? Is it fixed ? If it is fixed, just set "100%" to the img width. – Cesare Polonara May 01 '22 at 06:52
  • the container div is 100%. the slider div width is the sum of all image width. So the image width can not be 100%. All need to be dynamically calculated. – eastwater May 01 '22 at 06:55
  • 1
    if you only wanted to work with exact width number this page will help https://stackoverflow.com/questions/3877027/jquery-callback-on-image-load-even-when-the-image-is-cached but it should be easily done with `width:max-content` – Amir Rahman May 01 '22 at 07:08
  • You say that the slider width is the sum of images width, but you are trying to set image width based on container width, that makes no sense to me. Make a working snippet here maybe. – Cesare Polonara May 01 '22 at 07:29
  • It is image slider. img {float:left} – eastwater May 01 '22 at 08:44

1 Answers1

0

It is hard to tell why the width is changing according to your code... So I posted 3 solutions. Edit: After reading your comments, I believe solution 2 is what you are looking for.

Solution 1 - using vw

The simple solution should be setting the image width to 100vw in css like so: #img {width=100vw}

Solution 2 - update in window.onload

Usually window.onload = () => {} will do. Here is why:

image load vs. DOM load

It appears that the image load time might effect your container size. When using ready the code initiates before waiting for images to load. Then, your code runs before the images have their 'true' width. you should use $(window).on("load", handler)

With jQuery, you use $(document).ready() to execute something when the DOM is loaded and $(window).on("load", handler) to execute something when all other things are loaded as well, such as the images

Full explanation by paxdiablo

Solution 3 'hacky' - resize event listener

This is a kind of a 'hack' solution, though if all of the above won't work, it might work for you you (it is general as I'm not sure what causes the width changes in your code). Assuming you don't want the container size to keep changing always, but only after load. You could listen to changes for limited time, then turn them off:

const resize_ob = new ResizeObserver((entries) => {
    let rect= entries[0].contentRect;
    let width = rect.width;

    // here you can select all of its image children and adjust their size

});

let myDiv=window.getElementById("container")
resize_ob.observe(myDiv)

You could then turn of this event listener after some time, or as user interacted with your page somehow:

//end resize observation
resize_ob.unobserve(myDiv);

See detailed example here. Note that it is hacky, and as cesare-polonara mentioned:

probably will lead to weird behaviours used in that way since he won't listen to width change made programmatically

lior bakalo
  • 440
  • 2
  • 9
  • 1
    Could you explore the ResizeObserver option more? Why should you observe for container width change to handle children width, when you have css properties that can easily address that ? – Cesare Polonara May 01 '22 at 07:28
  • Well asked. This is solution 1. Yet, I assumed he wants to stops changing the container size at some point. so I added this, where he could listen to changes (for example first 10 seconds, or until user clicks something) then turn it off.I updated answer. – lior bakalo May 01 '22 at 07:31
  • 1
    That sounds pretty hacky and probably will lead to weird behaviours used in that way since he won't listen to width change made programmatically, but to width change due to image not being still loaded if I understood correctly. I still think that he is handling the scenario in a wrong way in CSS. In any case the ResizeObserver callback passes an array of entries as param, not the observed element. – Cesare Polonara May 01 '22 at 07:56
  • Well thanks, I'll update the answer. It is hacky as in not sure what causes him the problem – lior bakalo May 01 '22 at 08:01
  • 1
    Thanks. I tried Solution 1, 2 and 3. But none of them works in my case. image width 100vw is not the same as the container width. Same as document.ready, window.on("load", function) gives me different container width (not stable). ResizeObserver: within the callback, the container div width is changed from 1919 to 20336014. In my code, the container width is set to 100% every time trying to get the container width. – eastwater May 01 '22 at 09:06
  • I'm sorry to hear it didn't work, I was sure that it is the onload.. if you can edit your answer with code snipped/link to your source code I'll try again – lior bakalo May 01 '22 at 09:08