Thursday, February 9, 2012

Prevent overscroll on iOS Safari

iOS 5.x Safari supports single-finger scrolling of the contents of a DIV or IFRAME. However, scrolling that DIV too far makes your entire page scroll as well. This behavior is undesirable if the page was specifically designed to fill the mobile screen. I've seen some heavy-handed solutions to this, including disabling all scrolling and using iScroll 4 to simulate it.

Below is my solution.  This leverages the browser's own scrolling mechanisms and adds minimal runtime overhead, so scrolling stays lightweight, portable, and efficient.  The caller includes this script and then says something like:

<script>
  // This must be during the bubble phase (i.e., last argument =
  // false) so that inner objects have an opportunity to override it.
  document.addEventListener('touchmove', function(e) { e.preventDefault(); }, false);
  var scroller = document.getElementById('scroller');
  preventOverScroll(scroller);
</script>

at the bottom of the HTML document.

preventOverScroll.js


/**
 preventOverScroll.js

 Prevents iOS 5.0 Safari scrolling elements from causing the page itself
 to scroll.

 Permission granted to use this code under the Open Source MIT License.
 http://www.opensource.org/licenses/mit-license.php
Copyright (c) 2012 Morgan McGuire
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


 http://casual-effects.com
*/


/** Invoke on a DIV that is set to touchscroll by the CSS properties:
    
      -webkit-overflow-scrolling: touch;
      overflow: scroll;

    iOS Safari has a quirk that dragging a scrolling element upwards
    past its top or downwards past its bottom will cause the entire
    page to scroll, including even position: fixed elements.  This
    only happens if the scroll starts at the limit; if the element
    begins the scrolling process somewhere in the middle, scrolling
    past the top or bottom does not affect the page.  This does not
    happen at all for horizontal scrolling.
    
    To prevent this behavior, we detect when a touch on a scrolling
    element begins at the limit and disable scrolling in that
    direction specifically.
    
    The containing element must disable default behavior during the
    bubble phase of touchmove delivery, e.g.,
    
      document.addEventListener('touchmove', function(e) { e.preventDefault(); }, false);
    
    Warning: This may have issues with multiple touches; I'm assuming
    that the touch seen in touchmove was the same as the one in
    touchstart.  However, once the second touch begins, we're not in
    single-finger scrolling, so maybe it doesn't matter.  
*/
function preventOverScroll(scrollPane) {
    var CAPTURE_PHASE = true// happens first, outside to inside
    var BUBBLE_PHASE  = false; // happens second, inside to outside

    // These variables will be captured by the closures below
    var allowScrollUp = true, allowScrollDown = true, lastY = 0;

    scrollPane.addEventListener
    ('touchstart',
     function(e) { 
         
         allowScrollUp = (this.scrollTop > 0);
         allowScrollDown = (this.scrollTop < this.scrollHeight - this.clientHeight);
         
         // Remember where the touch started
         lastY = e.pageY;
     }, 
     CAPTURE_PHASE);

    // If the touch is on the scroll pane, don't let it get to the
    // body object which will cancel it
    scrollPane.addEventListener
    ('touchmove'
     function (e) {
         var up   = (e.pageY > lastY);
         var down = ! up;
         lastY    = event.pageY;
         
         // Trying to start past scroller bounds
         if ((up && allowScrollUp) || (down && allowScrollDown)) {
             // Stop this event from propagating, lest 
             // another object cancel it.
             e.stopPropagation(); 
         } else {
             // Cancel this event
             e.preventDefault();
         }
     }, 
     CAPTURE_PHASE);
};



Morgan McGuire is a professor of Computer Science at Williams College and a professional game developer. He is the Editor in Chief of the Journal of Computer Graphics Techniques and the author of The Graphics Codex, an essential reference for computer graphics that runs on iPhone, iPad, and iPod Touch.

6 comments:

  1. Thank you so much for this! I've been tearing my hair out trying to figure out how to prevent the darn body overscrolling when working with an inner scrolling div, and this worked exactly as I needed.

    ReplyDelete
  2. Hi Morgan,
    Thanks for publishing this. It's the only useful starting point that I could find on this infuriating problem. Most answers assume you don't want to scroll *anything*.
    I am confused about a couple of things though. You're defining a BUBBLE_PHASE constant, but then never using it. Is that in fact meant to be used in one of the event listeners?
    In that second event listener you are reading the window.event property rather than the scoped e variable. Is there a reason for this?

    ReplyDelete
    Replies
    1. BUBBLE_PHASE is just to show the other value that one might pass to the handler registration, which is not needed here.

      'event' was a typo and I just corrected it.

      Delete
  3. Hi Morgan,

    Thanks for publishing. I used your code in combination with the fastclick.js by Financial Times. This introduced a bug: at the end of a scroll event a click for registered. To fix this I added the following code to your function:

    scrollPane.addEventListener
    ('touchend',
    function (e) {
    e.stopPropagation();
    },
    CAPTURE_PHASE);

    ReplyDelete
  4. Finaly a light weight solution that works! Works good with JQM
    One thing is i've been on this page a few times, but always skipped it due to the fact that the code was unreadable and I had to zoom in to read it..
    Using chrome, 24inch screen 1920x1200 res..
    Anyways thanks a bunch!

    ReplyDelete
  5. thank you for your great work!

    ReplyDelete

Note: Only a member of this blog may post a comment.