Tuesday, December 30, 2014

Javascript to Zoom According to a Maximum Browser's Width


There will be times when you need to perform some zooming on the browser so that you'll see what things will look like in other resolutions. For example, if you need to know how your website looks like on an iPhone screen, you might this Javascript function that I am going to show you. But make sure you know the target screen resolution before you try the following codes out:

<html>
<script>

var width,zoomPercentage;

function setWidth(pixel) {

 if (!pixel) {
  zoomPercentage = 100;
 }
 else {
  if (navigator.userAgent.indexOf("MSIE") != -1) { // IE
   width = document.documentElement.offsetWidth;
  }
  else {
   width = document.getElementsByTagName("body")[0].clientWidth;
  }
  zoomPercentage = Math.round((width/pixel)*100);
 }

 document.body.style.zoom = zoomPercentage+"%";
}

</script>

<body>

Hello World!<br>

<a href="javascript:setWidth(800)">800 pixel</a> <a href="javascript:setWidth(1024)">1024 pixel</a> <a href="javascript:setWidth(1280)">1280 pixel</a> <a href="javascript:setWidth(1920)">1920 pixel</a> <a href="javascript:setWidth(0)">default pixel</a>

<br><img src="http://www.freeimageslive.com/galleries/backdrops/colourful/pics/background01331.jpg">

</body>
</html>



You can replace your HTML codes to replace the image I inserted to see the zoom effect clearly. Please note that the most important part of the codes is in green text. Please also note that these codes may not run well in all IE versions. It is recommended to use a non-IE browser to try it out.

No comments:

Post a Comment