61

For a map-like tool, I would like to disable the browser zooming feature. (I know that this is generally a bad idea, but for some specific website, it is needed).

I did it successfully by listening the keyboard shortcut CTRL + / CTRL - and adding e.preventDefault(), etc. But this doesn't prevent from changing the zoom from the browser's Zoom menu.

I tried:

  • with CSS: zoom: reset; It works for Chrome (see this page for a working example) but it doesn't work at all on Firefox.

  • in various questions/answers, I also found

    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

    but this seems to work for mobile only.


How to prevent zooming cross-browser ?

Basj
  • 29,668
  • 65
  • 241
  • 451
  • @Skoua: it's possible to override these shortcuts. I successfully did (with `window.onkeydown` and `e.preventDefault()`). My question is : how to prevent from zooming from the browser's menu (View > Zoom settings, etc.) – Basj Nov 25 '14 at 08:46
  • just listen to '**ctrl**' combined with '**mouse wheel**' - most users zoom in and out while holding ctrl down and scrolling the wheel.. for those who go all the way to the menu to zoom in / out - let them be :) – ymz Nov 27 '14 at 23:59
  • 1
    If this was on flash, it would be a different story. Regardless, I've been trying to build a script that detects the browser's zoom level and applies the opposite effect with css using `zoom` but it's more difficult than I thought. (using http://tombigel.github.io/detect-zoom/) – chdltest Nov 28 '14 at 00:23
  • I can just as easily resize my browser window, or change my resolution, which layout wise has the same effect as zooming. So what are you actually trying to prevent? Are you really trying to make your site only work with one resolution? – David Nov 29 '14 at 21:27
  • @David: here is my website, you will see why I want to avoid "standard" browser zooming : http://bigpicture.bi/demo – Basj Nov 30 '14 at 00:11
  • @Basj, good reason. There's still no way to do stop it, but it looks like there is a way to counteract it, which I just put into an answer. – David Nov 30 '14 at 02:05
  • You could technically make all sizes relative so scrolling wouldn't do anything. – Slava Knyazev Nov 30 '14 at 02:07
  • Also worth noting that some of us who have high res monitors have a default zoom value that isn't 100% - so even if you detect the zoom change event, you're not starting from a known position – Basic Nov 30 '14 at 02:14
  • @Basj Nice app, but I don't see the gain from preventing browser zoom. (I see that it doesn't make sense to use browser zoom when using the app, but that's not the same thing.) – hon2a Dec 01 '14 at 15:27
  • @Basj: Just don't do this. Seriously. Parts of your app as things stand border on unreadable for old, tired eyes. Disabling zooming serves absolutely no point except irritating users. (Also, tbh, overriding the scroll to make things zoom in and out is awkward to the point that your site ended up being a useless white screen within 10s of me trying it and getting lost in it.) – Denis de Bernardy Dec 03 '14 at 14:15
  • @Denis you have "click on the BigPicture logo" or the keyboard shortcut "F2" for that : it would bring you back to "see the bigpicture" : http://bigpicture.bi/demo . Something else: I don't understand a part of your comment: if unreadable, just use the zooming that I provide in the app (instead of the browser internal zoom that makes no sense in this app) – Basj Dec 03 '14 at 19:55
  • @Basj, don't forget to award the bounty to whoever helped the most. – David Dec 05 '14 at 10:02
  • Yes @David I will award it. Currently here : http://gget.it/vtn8i8rb/NFB92BF.HTML, only CTRL+ / CTRL- is disabled. Can we update it, as much as we can (of course, it won't work on every browser) with the different techniques provided here? – Basj Dec 05 '14 at 11:45
  • @Basj, I see your demo has zoom disabled, at least on the navbar. And it seems disabled even on Firefox desktop. How'd you finally manage it? – Yash Capoor Jul 05 '17 at 12:29
  • Maybe it's a matter of **[detecting](https://stackoverflow.com/questions/995914/catch-browsers-zoom-event-in-javascript) zoom** and then scaling the elements accordingly – Samy Bencherif Jul 05 '17 at 22:27
  • For what it’s worth, as of this writing, it appears that `zoom: reset` not even supported in Chrome anymore (I’m using Chrome 77). – JakeRobb Jul 15 '19 at 20:29

9 Answers9

39

I haven't really found an "authoritative" answer, meaning a clear statement from browser developers. However, all answers to similar questions I've found (like this one or that one) suggest the same thing - the browser's zoom feature exists for the benefit of the users and some browsers (like Firefox) simply don't allow you, as a website creator, to take this option away from them.


This documentation might shed some light into why allowing authors to disable zoom might be a good idea on mobile devices, but not on desktops.

In short, you might need to prevent mobile devices from initially auto-zooming your website, if you know their calculated auto-zoom will be inappropriate. On desktops, there is no auto-zoom, so when users come to your website, they see it exactly as it was meant to be seen. If they then decide they need to zoom the page, there's no good reason to let you prevent them from doing so.


As for the solutions you've listed:

Community
  • 1
  • 1
hon2a
  • 6,515
  • 5
  • 38
  • 52
  • 1
    The app you've linked in a question comment is all about zoom, which makes my answer less relevant to your particular situation. Still, it may be helpful in general, I guess. – hon2a Dec 01 '14 at 15:30
38

You can disable zoom in browser by Ctrl+ or Ctrl- or Using Ctrl Key + Mouse wheel Up or down by this code.

$(document).keydown(function(event) {
if (event.ctrlKey==true && (event.which == '61' || event.which == '107' || event.which == '173' || event.which == '109'  || event.which == '187'  || event.which == '189'  ) ) {
        event.preventDefault();
     }
    // 107 Num Key  +
    // 109 Num Key  -
    // 173 Min Key  hyphen/underscor Hey
    // 61 Plus key  +/= key
});

$(window).bind('mousewheel DOMMouseScroll', function (event) {
       if (event.ctrlKey == true) {
       event.preventDefault();
       }
});

Check a demo here http://jsfiddle.net/VijayDhanvai/4m3z3knd/

Vijay Dhanvai
  • 978
  • 2
  • 10
  • 22
8

I think what you can do is, listen to browser zoom event(ctrl + "+") and then check for window.devicePixelRatio.

Then accordingly, apply HTML5 scale transformation on the body element to scale down by the same ratio. So, basically you cannot prevent the functionality but you can apply negative effect with the same magnitude.

POC Code:

 <body style="position: absolute;margin: 0px;">
        <div style="width: 300px; height: 200px; border: 1px solid black;">
            Something is written here
        </div>
        <script>
            var keyIncrease = [17, 61];
            var keyDecrease = [17, 173];
            var keyDefault = [17, 48];
            var listenMultiKeypress = function(keys, callback){
                var keyOn = [];
                for(var i=0; i<keys.length; i++){
                    keyOn[i] = false;
                }
                addEventListener('keydown', function(e){
                    var keyCode = e.which;
                    console.log(keyCode);
                    var idx = keys.indexOf(keyCode);
                    if(idx!=-1){
                        keyOn[idx] = true;
                    }
                    console.log(keyOn);
                    for(var i=0; i<keyOn.length; i++){
                        if(!keyOn[i]){
                            return;
                        }
                    }
                    setTimeout(callback, 100);
                });
                addEventListener('keyup', function(e){
                    var keyCode = e.which;
                    var idx = keys.indexOf(keyCode);
                    if(idx!=-1){
                        keyOn[idx] = false;
                    }
                    console.log(keyOn);
                });
            };
            var previousScale = 1;
            var previousDevicePixelRatio;
            var neutralizeZoom = function(){
                //alert('caught');
                var scale = 1/window.devicePixelRatio;

                document.body.style.transform = 'scale('+(1/previousScale)+')';
                document.body.style.transform = 'scale('+scale+')';
                var widthDiff = parseInt(getComputedStyle(window.document.body).width)*(scale-1);
                var heightDiff = parseInt(getComputedStyle(window.document.body).height)*(scale-1);
                document.body.style.left = widthDiff/2 + 'px';
                document.body.style.top = heightDiff/2 + 'px';
                previousScale = scale;
            };

            listenMultiKeypress(keyIncrease, neutralizeZoom);
            listenMultiKeypress(keyDecrease, neutralizeZoom);
            listenMultiKeypress(keyDefault, neutralizeZoom);
            neutralizeZoom();
        </script>
    </body>
</html>
thunder
  • 220
  • 1
  • 8
7

Insert the following into your HTML:

For Mobiles: Insert between the '< head>...< /head>' tag.

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">

For Desktops across-Browsers: Insert just after start '< body>...' tag.

<script>
  document.body.addEventListener("wheel", e=>{
    if(e.ctrlKey)
      e.preventDefault();//prevent zoom
  });
</script>
Will Munn
  • 5,693
  • 4
  • 22
  • 28
Jeremy Levett
  • 691
  • 7
  • 11
6

So, as has been mentioned, that really isn't possible. However, there are some ways you can still be smart about it.

Three of the five major browsers all allow you to see the zoom level of the browser, furthermore, should the browser be zoomed a window.onresize event is fired.

IE:      event.view.devicePixelRatio           OR window.view.devicePixelRatio
Chrome:  event.currentTarget.devicePixelRatio  OR window.devicePixelRatio
Firefox: event.originalTarget.devicePixelRatio OR window.devicePixelRatio
Safari:  /* Not possible */
Opera:   /* Not possible */

I think the stuff after OR works based on something I noticed as I was messing around. The first ones I know work in at least the latest version of each one. Note that Safari and Opera both have the devicePixelRatio, however both never change. It's always just 1.

The above is your easy way if you don't care that much. If you do, then you could try out the detect-zoom script, which I came across while looking for solutions to Safari and Opera.

So what you can now do is get the zoom level, and then offset your zoom to where it doesn't do anything. So if I force my browser to 50% zoom, you just go to 200%. Thus, no change. Of course it will be a bit more complicated, you'll have to store the last browser zoom, the new browser zoom, and do some slightly more complicated math, but based on what you already have, that should be a breeze.

Another idea might be to just listen for a resize event, and calculate based off the new visible size, but that might cause issues if the window is just resized. I think the above is going to be your best option, with perhaps a fallback alert to warn the user not to zoom if necessary.

David
  • 4,249
  • 5
  • 27
  • 56
  • This is probably the best way to go about and covers all scenarios. And the `detect-zoom` script does not work with new versions of Chrome and Firefox. But as stated, Safari and Opera are supported. – stackErr Nov 30 '14 at 02:38
  • Do you think @David it could be possible to update this HTML page http://gget.it/vtn8i8rb/NFB92BF.HTML, so that zooming is disabled, as much as we can (of course, it won't work on every browser) with the techniques you propose here? Currently on this page only CTRL + / CTRL - is disabled – Basj Dec 05 '14 at 11:41
  • @Basj, the methods mentioned in this post are reliant on your design. The properties are read only, so the best you're going to be able to do is counteract them. E.g. if you're at `223%` zoom, and the user changes it to `150%` zoom, you'd then read that, and go to `1.486%` zoom on your code. (If I'm doing the math right: `223/150`). If the user changes again, then you'd pretent `150%` is `100%` and do the math based off of that. Something like the page you've given is straight text, so that doesn't work. Furthermore, you wouldn't want to prevent zoom on that type of page. – David Dec 05 '14 at 13:48
4

I updated code Vijay code:

$(document).ready(function(){
 var keyCodes = [61, 107, 173, 109, 187, 189];

 $(document).keydown(function(event) {   
   if (event.ctrlKey==true && (keyCodes.indexOf(event.which) != -1)) {
     alert('disabling zooming'); 
     event.preventDefault();
    }
 });

 $(window).bind('mousewheel DOMMouseScroll', function (event) {
    if (event.ctrlKey == true) {
      alert('disabling zooming'); 
      event.preventDefault();
    }
  });
});

This solution is cross-platform (OS / Win) for desktop browsers.

Andrii Gordiichuk
  • 1,179
  • 9
  • 10
  • I pasted your code into jsfiddle.net and I can still zoom on a mac using Command + – PioneerMan Aug 04 '16 at 21:56
  • @NestMan, I think you forgot put }); in the end. – Andrii Gordiichuk Dec 04 '17 at 15:38
  • This prevents it from zooming, great job, but if you really try to scroll zoom it still zooms on chrome. –  Apr 01 '18 at 17:25
  • On my macbook, I pinch out on trackpad (moving two fingers on trackpad from each other at the same time) - browser calls "mousewheel" event and the script does not work, because crtlKey is not pressed (neither Cmd key). – Maxim Georgievskiy Feb 03 '21 at 18:34
1

Have you tried ...

$("body").css({
     "-moz-transform":"scale(1)",
     "-webkit-transform":"scale(1)",
     "-o-transform":"scale(1)",
     "-ms-transform":"scale(1)"
});

I've used this type of code to set or re-set the scale.

Eray Balkanli
  • 6,960
  • 9
  • 39
  • 65
rfornal
  • 4,842
  • 5
  • 27
  • 41
1
$(document).ready(function () {
      $(document).keydown(function (event) {
          if (event.ctrlKey == true && (event.which == '107' || event.which == '109' || event.which == '187' || event.which == '189'))
           {
               event.preventDefault();
           }
       });

           $(window).bind('mousewheel DOMMouseScroll', function (event) {
               if (event.ctrlKey == true) {
                   event.preventDefault();
               }

      });
  })
Shanu Shaji
  • 134
  • 1
  • 11
1

It is simple:

function load(){
  document.body.addEventListener("wheel", zoomShortcut); //add the event
}

function zoomShortcut(e){
  if(e.ctrlKey){            //[ctrl] pressed?
    event.preventDefault();  //prevent zoom
    if(e.deltaY<0){        //scrolling up?
                            //do something..
      return false;
    }
    if(e.deltaY>0){        //scrolling down?
                            //do something..
      return false;
    }
  }
}
p {
  display: block;
  background-color: #eeeeee;
  height: 100px;
}
<!DOCTYPE html>
<html>
  <head>
    <title>Mousewheel control!</title>
  </head>
  <body onload="load()">
    <p>If your Mouse is in this Box, you can't zoom.</p>
  </body>
</html>
B. Colin Tim
  • 203
  • 2
  • 12