Determining the width of a webpage in inches

I have a CSS stylesheet that uses media queries to change how a page is displayed based on how many inches it is in width (for instance, if it is smaller than 4 inches or being displayed on a handheld device, it assumes a more mobile-friendly LAF).

The problem I have is with its content. On the homepage, there is a dock-style interface that dynamically changes height based on the current height and width of the window so that the text and items never leave the screen. However, my JS that determines this size does not know when the stylesheet has changed for handheld devices or small screens, so the behavior continues unpredictably in this mode. How can I use JavaScript detect when the page is less than or equal to 4 inches so that I can disable the auto-resizing of the then-reformed dock?

Answers:

Answer

It's a non-trivial problem.

Here's a link to a site that has a function (getUnits) to get the current computed style in a measurement unit of your choice (including inches) http://upshots.org/javascript/javascript-get-current-style-as-any-unit

Using this function, you could check if (getUnits(document.body, "width").inch < 4). The way this function works, for the curious, is by creating a temporary element in the desired measurement space and reading off the ratio to pixels. In this way you let the browser respond based on its own knowledge the device's PPI. So this is sort of a polyfill for window.devicePixelRatio, however browsers mostly lie about their PPI. For these purposes, though, it doesn't matter since they will be applying the same lie to your inch-unit CSS.

Answer

I don't test this on real browsers, but it should work:

  1. set a hidden <div id="screen" style="display:none"> in your HTML.

  2. In CSS, use media query like:

      @media screen
      { div#screen{color: blue;} }
    
      @media screen and (min-width: 13in)
      { div#screen{color: red;} }
    

Then you can read the div#screen color in JS to choose the actions.

Also, you should take windows resize event into JS consideration.

Answer

All you can do is read back the current style of a known element. By looking at something such as the width of an outer-wrapper DIV you can determine which stylesheet in your media query is in use.

Answer

I think you're looking at the problem from the wrong angle. You shouldn't be thinking about inches. What you need to know is: given the device and browser how many pixels high should my page be?

The answer will lie in keeping a known set of devices and their respective pixel height.

An iPhone 5 is taller than an iPhone 4 for instance, this affects the effect you're going for.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.