Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading