How can I get the user display size? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How can I get the user display size?

I'm using percentages in "width" and "height" properties. How can I get them in pixels using JS? something like that: //totally inaccurate, it's just for explaining <div style="height:80%; width:50%;" id="ex">Text</div> <script> var el = document.getElementById("ex"); /*What I want: */ el.style.fontSize = el.pixelHeight+"px"; <script> I hope you understand :P

14th Jan 2017, 4:29 PM
IgorSM
IgorSM - avatar
9 Answers
+ 11
<div style="height:80vw; width:50vw;" id="ex">Text</div> <script> var el = document.getElementById("ex"); el.style.fontSize = el.style.width; <script> /* do it like this, "vw" is the same as "%" */
14th Jan 2017, 5:28 PM
Valen.H. ~
Valen.H. ~ - avatar
+ 9
What number does "el.style.style.width" return?
14th Jan 2017, 5:16 PM
Valen.H. ~
Valen.H. ~ - avatar
+ 5
Access to style property of html element access only to it's inlining style property declaration: if another rule apply, the property doesn't return good value... and unit of returned value is unit of rules ( so @VH solution works because unit is percetage of viewport width instead of parent witdth, but does'nt apply a 'px' unit to font-size style ^^ ) Solution is to use window.getComputedStyle() function, which return the 'px' computed value ( whatever the place of the rules applyed definition is ): var el=document.getElementById('el_id'); var st = window.getComputedStyle(el); document.write(st.width); The return type value is a string, with 'px' appending: if 'el_id' element has a style rule declaration setting a % value, you'll get kind of: 102.5px
14th Jan 2017, 6:09 PM
visph
visph - avatar
+ 3
el.style.width? Can you tell me what is "el"?
14th Jan 2017, 5:13 PM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
+ 3
No, I mean what is that element. I would suggest you to publish the code and make this debugging question.
14th Jan 2017, 5:15 PM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
+ 3
jQuery way? $(document).ready(function(){ var $width=$("#el").width(); });
14th Jan 2017, 5:43 PM
Iván
Iván - avatar
+ 2
el.width?
14th Jan 2017, 5:05 PM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
+ 1
great, returns "undefined"
14th Jan 2017, 5:12 PM
IgorSM
IgorSM - avatar
+ 1
el = element
14th Jan 2017, 5:14 PM
IgorSM
IgorSM - avatar