document.ontouchmove and scrolling on iOS 5

ghenne picture ghenne · Oct 17, 2011 · Viewed 60.7k times · Source

iOS 5 has brought a number of nice things to JavaScript/Web Apps. One of them is improved scrolling. If you add

-webkit-overflow-scroll:touch;

to the style of a textarea element, scrolling will work nicely with one finger.

But there's a problem. To prevent the entire screen from scrolling, it is recommended that web apps add this line of code:

document.ontouchmove = function(e) {e.preventDefault()};

This, however, disables the new scrolling.

Does anyone have a nice way to allow the new scrolling within a textarea, but not allow the whole form to scroll?

Answer

Brian Nickel picture Brian Nickel · Oct 17, 2011

Update Per Alvaro's comment, this solution may no longer work as of iOS 11.3.

You should be able to allow scrolling by selecting whether or not preventDefault is called. E.g.,

document.ontouchmove = function(e) {
    var target = e.currentTarget;
    while(target) {
        if(checkIfElementShouldScroll(target))
            return;
        target = target.parentNode;
    }

    e.preventDefault();
};

Alternatively, this may work by preventing the event from reaching the document level.

elementYouWantToScroll.ontouchmove = function(e) {
    e.stopPropagation();
};

Edit For anyone reading later, the alternate answer does work and is way easier.