Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

369
Visualizações
jquery/javascript: when to get the correct container div size?

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

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda