How to programmatically determine the current zoom level of the browser window?

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

+5
source share
2 answers

You can determine the zoom level by comparing various properties with document.documentElement.clientWidthdepending on your browser:

  • against. window.outerWidth(in Opera)
  • against. document.defaultView.getComputedStyle(document.documentElement, null).width(in Safari, Chrome)
  • or compare screen.deviceXDPIand screen.logicalXDPI(in IE8).

The ratio of these values ​​represents the current zoom level (for example, a ratio of 2 indicates a 200% increase).

+1
source

, , ( ) , 100%. jquery, , ( 15 , , -, ).

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); 
}

, , . , , , .

0

All Articles