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

207
Visualizações
javascript pass screen width to function

I have implemented an infinite scroll and I need to modify the width of all elements to adjust to the display width.

the code is

 var elements = document.getElementsByClassName('myDiv');
 for (var i = 0; i < elements.length; i++) {
       elements[i].style.width = (screen.width / 2);
 }

and does not work (does not change the width of the div)

but

 var elements = document.getElementsByClassName('myDiv');
 for (var i = 0; i < elements.length; i++) {
       elements[i].style.width = "10px";
 }

works

and alert(screen.width) returns correctly the screen's width.

can someone help me ?

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

0

Add the px - the unit is expected

document.querySelectorAll('.myDiv')
  .forEach(div => div.style.width = `${(screen.width / 2)}px`)
.myDiv { background-color: yellow; }
<div class="myDiv" style="width:100px">Hello</div>
<div class="myDiv" style="width:200px">Hello</div>
<div class="myDiv" style="width:300px">Hello</div>
<div class="myDiv" style="width:400px">Hello</div>
<div class="myDiv" style="width:500px">Hello</div>
<div class="myDiv" style="width:600px">Hello</div>

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