Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get the width of the window in em units using javascript?

I'm looking for a reliable way to get the width of the window in em units using javascript. I was surprised to see that jQuery will only return a result in pixel measurements. Any help is appreciated.

like image 975
hammerbrostime Avatar asked Sep 03 '12 02:09

hammerbrostime


People also ask

How do we get the width of the web page in JavaScript?

Use window. innerWidth and window. innerHeight to get the current screen size of a page.

Can you use em in JavaScript?

Em units are extremely useful and are an essential component of responsive Web design (RWD). Unfortunately, browsers have failed to provide support for ems in JavaScript. I needed to reliably convert the pixel width value of an element to ems.

What is window innerWidth in JavaScript?

The read-only Window property innerWidth returns the interior width of the window in pixels. This includes the width of the vertical scroll bar, if one is present. More precisely, innerWidth returns the width of the window's layout viewport.

What is the unit of window innerWidth?

innerWidth returns a number in pixels, so you can just subtract 100 from it: var w = window. innerWidth - 100; Note that this will be negative, if the browser is under 100px in width.


2 Answers

This seems to work:

$(window).width() / parseFloat($("body").css("font-size")); 
like image 195
hammerbrostime Avatar answered Sep 21 '22 15:09

hammerbrostime


Here's a solution that doesn't require jQuery, and doesn't require an explicit font-size declaration.

window.innerWidth / parseFloat(   getComputedStyle(     document.querySelector('body')   )['font-size'] ) 
like image 45
Brad Avatar answered Sep 20 '22 15:09

Brad