Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!