javascriptscrollzoomingevent-listenertouchpad

Disable Pinch Zoom but Allow Scroll with JavaScript


TL;DR: I need a JavaScript solution that disables pinch-zooming but preserves vertical two-finger scrolling on touchpads.


Generally speaking, on devices with touchpads - like laptops! - users are able to “zoom in” to a webpage by simply pinching or spreading two fingers. Additionally, users have the ability to scroll down a page by just using two fingers. This is called “two-finger scrolling.”


Some Context

I've been developing an online application that relies on a specific zooming feature as part of its functionality.

Since a major part of the application was to zoom in on a grid, I needed to disable this automatic pinch-to-zoom gesture that annoyingly zoomed into the actual content of the page, as opposed to the grid itself.

What I've Tried Already

Thankfully, after doing a lot of research, I finally found an answer that prevents users from being able to pinch-to-zoom. And what a relief, it actually works. (Code shown below)

JavaScript
window.addEventListener('wheel', event => {
    event.preventDefault() // Disable default behaviour
},{
    passive: false // Very important. Can be easy to overlook 
})

The Problem

This approach works well. However, the current issue is that - although this code does indeed disable pinch-zooming on a touchpad - it also disables standard two-finger scrolling. As a result, for devices with touchpads, some major text-based parts of my application are completely hidden from view, since two-finger scrolling also gets disabled.


I am looking for a JavaScript solution for touchpads that disables pinch-zooming but preserves two-finger scrolling. Am I missing something obvious in the code? Will I need to detect each finger input manually for this to work? Open to any suggestions!

Please note: I'm aware that it's generally discouraged to disable pinch-zoom on a webpage, but it is necessary for this application, as previously explained.

Thanks in advance!!


Solution

  • One difference between wheel events that scroll and zoom seems to be that ctrlKey is set to true automatically in those events. With that knowledge, you could try this:

    window.addEventListener( 'wheel', event => {
    
      if( event.ctrlKey ) event.preventDefault()
      
    }, { passive: false })
    html, body {
      height: 100%;
    }
    body {
      padding: 0;
      margin: 0;
    }
    div {
      height: 500vh;
      width: 100%;
      font-family: monospace;
      font-size: 10vw;
      background: linear-gradient(0deg, gray, white);
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    div span {
      position: sticky;
      top: 0;
    }
    div span + span {
      bottom: 0;
      margin-top: auto;
    }
    <div>
      <span>Zoom me</span>
      <span>You cannot</span>
    </div>

    That seems to do the trick.