Changing the browser zoom level

JavascriptBrowserZooming

Javascript Problem Overview


I have need to create 2 buttons on my site that would change the browser zoom level (+) (-). I'm requesting browser zoom and not css zoom because of image size and layout issues.

Well, is this even possible? I've heard conflicting reports.

Javascript Solutions


Solution 1 - Javascript

Possible in IE and chrome although it does not work in firefox:

<script>
   function toggleZoomScreen() {
       document.body.style.zoom = "80%";
   } 
</script>

<img src="example.jpg" alt="example" onclick="toggleZoomScreen()">

Solution 2 - Javascript

I would say not possible in most browsers, at least not without some additional plugins. And in any case I would try to avoid relying on the browser's zoom as the implementations vary (some browsers only zoom the fonts, others zoom the images, too etc). Unless you don't care much about user experience.

If you need a more reliable zoom, then consider zooming the page fonts and images with JavaScript and CSS, or possibly on the server side. The image and layout scaling issues could be addressed this way. Of course, this requires a bit more work.

Solution 3 - Javascript

Try if this works for you. This works on FF, IE8+ and chrome. The else part applies for non-firefox browsers. Though this gives you a zoom effect, it does not actually modify the zoom value at browser level.

    var currFFZoom = 1;
	var currIEZoom = 100;
	
	$('#plusBtn').on('click',function(){
		if ($.browser.mozilla){
			var step = 0.02;
			currFFZoom += step; 
			$('body').css('MozTransform','scale(' + currFFZoom + ')');
		} else {
			var step = 2;
			currIEZoom += step;
			$('body').css('zoom', ' ' + currIEZoom + '%');
		}
	});
	
	$('#minusBtn').on('click',function(){
		if ($.browser.mozilla){
			var step = 0.02;
			currFFZoom -= step; 				
			$('body').css('MozTransform','scale(' + currFFZoom + ')');
			
		} else {
			var step = 2;
			currIEZoom -= step;
			$('body').css('zoom', ' ' + currIEZoom + '%');
		}
	});

Solution 4 - Javascript

You can use the CSS3 zoom function, but I have not tested it yet with jQuery. Will try now and let you know. UPDATE: tested it, works but it's fun

Solution 5 - Javascript

I could't find a way to change the actual browser zoom level, but you can get pretty close with CSS transform: scale(). Here is my solution based on JavaScript and jQuery:

<!-- Trigger -->
<ul id="zoom_triggers">
	<li><a id="zoom_in">zoom in</a></li>
	<li><a id="zoom_out">zoom out</a></li>
	<li><a id="zoom_reset">reset zoom</a></li>
</ul>

<script>
	jQuery(document).ready(function($)
	{
		// Set initial zoom level
		var zoom_level=100;

		// Click events
		$('#zoom_in').click(function() { zoom_page(10, $(this)) });
		$('#zoom_out').click(function() { zoom_page(-10, $(this)) });
		$('#zoom_reset').click(function() { zoom_page(0, $(this)) });

		// Zoom function
		function zoom_page(step, trigger)
		{
			// Zoom just to steps in or out
			if(zoom_level>=120 && step>0 || zoom_level<=80 && step<0) return;

			// Set / reset zoom
			if(step==0) zoom_level=100;
			else zoom_level=zoom_level+step;
			
			// Set page zoom via CSS
			$('body').css({
				transform: 'scale('+(zoom_level/100)+')', // set zoom
				transformOrigin: '50% 0' // set transform scale base
			});

			// Adjust page to zoom width
			if(zoom_level>100) $('body').css({ width: (zoom_level*1.2)+'%' });
			else $('body').css({ width: '100%' });

			// Activate / deaktivate trigger (use CSS to make them look different)
			if(zoom_level>=120 || zoom_level<=80) trigger.addClass('disabled');
			else trigger.parents('ul').find('.disabled').removeClass('disabled');
			if(zoom_level!=100) $('#zoom_reset').removeClass('disabled');
			else $('#zoom_reset').addClass('disabled');
		}
	});
</script>

Solution 6 - Javascript

as the the accepted answer mentioned, you can enlarge the fontSize css attribute of the element in DOM one by one, the following code for your reference.

 <script>
    var factor = 1.2;
    var all = document.getElementsByTagName("*");
    for (var i=0, max=all.length; i < max; i++) {
        var style = window.getComputedStyle(all[i]);
        var fontSize = style.getPropertyValue('font-size');

        if(fontSize){
            all[i].style.fontSize=(parseFloat(fontSize)*factor)+"px";
        }
        if(all[i].nodeName === "IMG"){
            var width=style.getPropertyValue('width');
            var height=style.getPropertyValue('height');
            all[i].style.height = (parseFloat(height)*factor)+"px";
            all[i].style.width = (parseFloat(width)*factor)+"px";
        }
    }
</script>

Solution 7 - Javascript

Not possible in IE, as the UI Zoom button in the status bar is not scriptable. YMMV for other browsers.

Solution 8 - Javascript

<html>
  <head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script>
        var currFFZoom = 1;
        var currIEZoom = 100;

        function plus(){
            //alert('sad');
                var step = 0.02;
                currFFZoom += step;
                $('body').css('MozTransform','scale(' + currFFZoom + ')');
                var stepie = 2;
                currIEZoom += stepie;
                $('body').css('zoom', ' ' + currIEZoom + '%');

        };
        function minus(){
            //alert('sad');
                var step = 0.02;
                currFFZoom -= step;
                $('body').css('MozTransform','scale(' + currFFZoom + ')');
                var stepie = 2;
                currIEZoom -= stepie;
                $('body').css('zoom', ' ' + currIEZoom + '%');
        };
    </script>
    </head>
<body>
<!--zoom controls-->
                        <a id="minusBtn" onclick="minus()">------</a>
                        <a id="plusBtn" onclick="plus()">++++++</a>
  </body>
</html>

in Firefox will not change the zoom only change scale!!!

Solution 9 - Javascript

You can use Window.devicePixelRatio and Window.matchMedia()

const onChange = e => {
  const pr = window.devicePixelRatio;
  const media = `(resolution: ${pr}dppx)`;
  const mql = matchMedia(media);

  const prString = (pr * 100).toFixed(0);
  const textContent = `${prString}% (${pr.toFixed(2)})`;

  console.log(textContent);
  document.getElementById('out').append(
    Object.assign(document.createElement('li'), {textContent})
  )

  mql.addEventListener('change', onChange, {once: true});
};

document.getElementById('checkZoom').addEventListener('click', e => onChange());

onChange();

<button id="checkZoom">get Zoom</button>
<ul id="out"></ul>

Solution 10 - Javascript

You can target which part of CSS zooming out and in, or the entire document.body.style.zoom

You can set the maximum and minimum zoom levels. Meaning, more clicks on the button (+) or (-) will not zoom in more or zoom out more.

var zoomingTarget = document.querySelector('.zooming-target')
var zoomInTool = document.getElementById('zoom-in');
var zoomOutTool = document.getElementById('zoom-out');

let zoomIndex = 0;

function zooming () {
    if (zoomIndex > 2) {
        zoomIndex = 2
    } else if (zoomIndex < -2) {
        zoomIndex = -2
    }
    zoomingTarget.style.zoom = "calc(100% + " + zoomIndex*10 + "%)";
}

Now make the buttons (+) and (-) work.

zoomInTool.addEventListener('click', () => {
    zoomIndex++;
    if(zoomIndex == 0) {
        console.log('zoom level is 100%')
    }
    zooming();
})

zoomOutTool.addEventListener('click', () => {
    zoomIndex--
    if(zoomIndex == 0) {
        console.log('zoom level is 100%')
    }
    zooming();
})

Since style.zoom doesn't work on Firefox, consider using style.transform = scale(x,y).

Solution 11 - Javascript

I basically change the zoom attribute in the body:

  private zoomPercentage = 100;

  increaseZoom() {
    this.zoomPercentage = Math.min(200, this.zoomPercentage + 1);
    this.updateZoom();
  }

  decreaseZoom() {
    this.zoomPercentage = Math.max(10, this.zoomPercentage - 1);
    this.updateZoom();
  }

  updateZoom() {
    document.body.style.setProperty(
      'zoom',
      `${this.zoomPercentage}%`
    );
  }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJourkeyView Question on Stackoverflow
Solution 1 - JavascriptCorne LukkenView Answer on Stackoverflow
Solution 2 - JavascriptEemeli KantolaView Answer on Stackoverflow
Solution 3 - JavascriptVijeyView Answer on Stackoverflow
Solution 4 - JavascriptobzennerView Answer on Stackoverflow
Solution 5 - JavascriptBogdanioView Answer on Stackoverflow
Solution 6 - JavascriptSalutonMondoView Answer on Stackoverflow
Solution 7 - Javascripti_am_jorfView Answer on Stackoverflow
Solution 8 - Javascriptamini gazarView Answer on Stackoverflow
Solution 9 - JavascriptExodus 4DView Answer on Stackoverflow
Solution 10 - JavascriptthaoView Answer on Stackoverflow
Solution 11 - JavascriptEliuXView Answer on Stackoverflow