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.
Use window. innerWidth and window. innerHeight to get the current screen size of a page.
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.
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.
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.
This seems to work:
$(window).width() / parseFloat($("body").css("font-size"));
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'] )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With