How to prevent vertical scrolling bounce of websites on iOS.

If you use your iPad and access any websites, you’ll notice that if you pull down on the content, you can drag the top of the page down an inch and then it will bounce back.  This is fine for most websites but in some cases this can be annoying e.g. I had a website that used divs to scroll through the content so  there was no content below or above the div.

I did some research and found ways to disable scrolling altogether by intercepting the touchstart or touchmove events and calling preventDefault() on the event.
After some experimentation and studying the touch events documentation, I found a near-perfect solution.

In simple terms, when your finger touches the screen, it fires the touchstart event.  I then capture the X/Y coordinates. As soon as your finger moves across the screen, it fires the touchmove event where I capture the new X/Y coordinates. I then check to see which way you are trying to move the page by comparing the movement along the X and Y axis.  If it’s vertical (change in Y > change in X), I call preventDefault(), which prevents the scroll.

Here’s the code:

var xStart, yStart = 0;

document.addEventListener('touchstart',function(e) {
     xStart = e.touches[0].screenX;
     yStart = e.touches[0].screenY;
});

document.addEventListener('touchmove',function(e) {
    var xMovement = Math.abs(e.touches[0].screenX - xStart);
    var yMovement = Math.abs(e.touches[0].screenY - yStart);
    if((yMovement * 3) > xMovement) {
        e.preventDefault();
    }
});