JavaScript Detect Web Page Zoom Level in Browsers – JavaScript Examples

By | December 7, 2020

We can press ctrl and + or ctrl and – to zoom in or zoom out a web page. In this tutorial, we will introduce you how to detect the zoom level using javascript.

JavaScript Detect Web Page Zoom Level in Browsers - JavaScript Examples

Here is an example code.

<script type="text/javascript"> 
function detectZoom(){ 
  var ratio = 0,
    screen = window.screen,
    ua = navigator.userAgent.toLowerCase();
 
   if (window.devicePixelRatio !== undefined) {
      ratio = window.devicePixelRatio;
  }
  else if (~ua.indexOf('msie')) {  
    if (screen.deviceXDPI && screen.logicalXDPI) {
      ratio = screen.deviceXDPI / screen.logicalXDPI;
    }
  }
  else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
    ratio = window.outerWidth / window.innerWidth;
  }
   
  if (ratio){
    ratio = Math.round(ratio * 100);
  }
   
   return ratio;
}
document.write(detectZoom());
</script>

Run this code, you will find:

If zoom in a web page, it will return a 100+ number.

If zoom out a web page, it will return a 100- number. That is zoom level.

Leave a Reply

Your email address will not be published. Required fields are marked *