CUTCODEDOWN
Minimalist Semantic Markup

Welcome Guest
Please Login or Register

If you have registered but not recieved your activation e-mail in a reasonable amount of time, please use our Contact Form for assistance. Include both your username and the e-mail you tried to register with.

Author Topic: JavaScript: Showing the width/height in EM  (Read 28 times)

Jason Knight

  • Administrator
  • Sr. Member
  • *****
  • Posts: 333
  • Karma: +36/-1
    • View Profile
    • CutCodeDown -- Minimalist Semantic Markup
JavaScript: Showing the width/height in EM
« on: 11 May 2020, 08:16:41 am »
Whilst a lot of browsers have extensions that will tell you the dimensions of the client area, it's sometimes nice to just be able to temporarily include a script to have it shown.

Code: [Select]
(function(d, w) {

var
dispX = d.body.appendChild(d.createElement('div')),
emSize;

dispX.setAttribute('style', '\
position:fixed;\
left:0;\
bottom:0;\
box-sizing:border-box;\
font:normal 1rem/1.5em arial,helvetica,sans-serif;\
padding:0.25em 0.5em;\
z-index:99999;\
background:#F00;\
color:#FFF;\
');

function dispXUpdate() {
dispX.textContent = 'Dim: ' +
(w.innerWidth / emSize) +
'em x ' +
(w.innerHeight / emSize) +
'em';
}

w.addEventListener('load', function() {
emSize = dispX.clientHeight / 2; // 0.25em top/bottom padding + 1.5em line-height == 2em
dispXUpdate();
w.addEventListener('resize', dispXUpdate, false);
}, false);

})(document, window);

What's nice about this is it tells you the value in BODY REM, which is what EM for your media queries should be, making it easier when resizing to determine your breakpoints. Just include this script right before </body> in your code when you want to take your responsive layout measurements.

I've used this script for years, and it's part of my normal workflow.

Also one of the few times I'd ever advocate setting style from the script, since this is a temporary tool not part of the page's normal codebase.
"It is amazing what can be accomplished when nobody cares who gets the credit." -- Kelly Johnson

 

Advertisement