How to detect zoom level in Opera

When I wrote the Autosizer User JavaScript, one of the things I needed to know was whether Opera’s viewport was zoomed, so that I could automatically adjust some margins and padding to ensure that images remained centered, no matter what zoom level the user had set his zoom level to.

The method I came up with, while not 100% accurate, works as a good approximation for moderate zoom levels.

How to measure

The method for measuring is really quite simple. A simple JavaScript run when a page has loaded can be used:

First, we create a fixed-position element with 100% height. Placing this off-screen is OK:

var d = document.createElement("div");
d.id="ozMeasure";
d.style="position:fixed;left:-100px;top:0;height:100%;width:1px";
document.documentElement.appendChild(d);

The next thing that happens is that we measure two different properties:

First we measure window.innerHeight - As long as the viewport size remains the same, this should stay unchanged. Next, we measure the offsetHeight of our newly created element, and here is where the magic happens:

While window.innerHeight yields a value that is the physical pixel height of the viewport, the offsetHeight of the created element yields the virtual or calculated value of the elements offsetHeight. Example:

If your viewport is 1000px tall, the offsetHeight will be 1000 at 100% zoom. When you zoom to 200%, this height will instead be 500. Zoom to 50%, and the offsetHeight will instead be 2000. In simple terms, this means that measuring the zoom level is reduced to dividing offsetHeight by window.innerHeight.

There is a demostration available — view source to see exactly what’s going on.

Comments

Comment from Anne on 2005-05-30 09:39

If you create a DIV of say 2^x pixels high shouldn’t you get the same effect? For example, if it’s 16 pixels high and you zoom to 200% it will be 32 pixels high or 8 pixels if you zoom to 50%.

Comment from Arve on 2005-05-30 10:12

If you create a block with a fixed pixel height, the offsetHeight stays the same I’m afraid. More precisely: The reason why offsetHeight changes when you zoom is because the virtual height of the viewport changes.

Comment from ROBO Design on 2005-06-07 12:43

Hello!
That’s nice. Nice trick :), even if it’s not 100% accurate. This might prove useful in quite a few User JavaScripts.

Comment from Emrah BASKAYA on 2005-09-03 14:18

I’ll try implementing this technique for my Multipopup script, I hope the fixed element does not cause scrolling slowdowns, I’ll have to inquire. Thanks for sharing this info, great insight.

This discussion has been closed. No further comments may be added.