6

I want to find out the zoom level of what is being displayed in a browser window based on the javascripts' window object properties to which I have access. I just can't seem to find the right mathematical formula for the zoom based on the inner width, page offset, etc. I found a solution, but that uses the document.body.getBoundingClientRect call which does not return anything in my case and for which I can't tell if there's a suitable replacement from the window properties. I am using Safari.

rekire
  • 47,260
  • 30
  • 167
  • 264
Mihai Fonoage
  • 478
  • 2
  • 8
  • 23

2 Answers2

1

You can determine zoom level by comparing various properties to document.documentElement.clientWidth depending on your browser:

  • vs. window.outerWidth (on Opera)
  • vs. document.defaultView.getComputedStyle(document.documentElement, null).width (on Safari, Chrome)
  • or compare screen.deviceXDPI and screen.logicalXDPI (on IE8).

The ratio of these values is the current zoom level (e.g. a ratio of 2 indicates a zoom of 200%).

John Feminella
  • 303,634
  • 46
  • 339
  • 357
-1

here's a rough estimate approach that determines zoom ratio by looking at the difference between the window's inner and available width (with and without the scrollbar), and compares that to what the scrollbar width should be at a 100% ratio. It currently depends on jquery, and some more work should be done to figure out the exact expected scrollbar width for various browsers (currently just using 15 pixels, which seems to be about the norm).

function getZoom(){ 

    var ovflwTmp = $('html').css('overflow');
    $('html').css('overflow','scroll');

    var viewportwidth;  
    // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight 
    if (typeof window.innerWidth != 'undefined')  {
        viewportwidth = window.innerWidth;
    } else if (typeof(document.documentElement) != 'undefined'  && 
        typeof document.documentElement.clientWidth != 'undefined' && 
        document.documentElement.clientWidth != 0) {
        // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document) 
        viewportwidth = document.documentElement.clientWidth; 
    } else { 
        // older versions of IE 
        viewportwidth = document.getElementsByTagName('body')[0].clientWidth; 
    }

    var windW = $(window).width();  
    var scrollBarW = viewportwidth - windW; 

    if(!scrollBarW) return 1;

    $('html').css('overflow',ovflwTmp);

    return  (15 / scrollBarW); 
}

While this isn't perfect, it's the best I've been able to come up with thus far for this kind of thing. I'm currently using it to know when to serve up high-resolution images, if the user has zoomed to the point of making them blurry.

user761574
  • 298
  • 3
  • 6