Disable Webpage Zooming by JavaScript

Aug. 03, 2024

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<script>
    document.addEventListener('wheel', function (e) {
      if (e.ctrlKey) {
        e.preventDefault();
      }
    }, {
      capture: false,
      passive: false 
    });

    document.addEventListener('keydown', function (event) {
      const zoomKeys = ['=', '+', '-', '_'];
      if ((event.ctrlKey || event.metaKey) && zoomKeys.includes(event.key)) {
        event.preventDefault();
      }
    }, false);  
</script>

Viewport meta tag1

The browser’s viewport is the area of the window in which web content can be seen. This is often not the same size as the rendered page, in which case the browser provides scrollbars for the user to scroll around and access all the content.

Some mobile devices and other narrow screens render pages in a virtual window or viewport, which is usually wider than the screen, and then shrink the rendered result down so it can all be seen at once. Users can then zoom and pan to look more closely at different areas of the page. For example, if a mobile screen has a width of 640px, pages might be rendered with a virtual viewport of 980px, and then it will be shrunk down to fit into the 640px space.

This is done because not all pages are optimized for mobile and break (or at least look bad) when rendered at a small viewport width. This virtual viewport is a way to make non-mobile-optimized sites in general look better on narrow screen devices.

However, this mechanism is not so good for pages that are optimized for narrow screens using media queries – if the virtual viewport is 980px for example, media queries that kick in at 640px or 480px or less will never be used, limiting the effectiveness of such responsive design techniques. The viewport meta element mitigates this problem of virtual viewport on narrow screen devices.

References