Search code examples
javascriptios6scrolliscroll

iScroll returns to top when touch event ends


I've got an iOS web app that is proving to be a really difficult with regards to scrolling! The closes I have come to solving the issue is with iScroll 4. However when I remove my finger from the screen the scrolling part seems to return back to its original position.

Anybody got any ideas on why this might be and how to fix it?

The Script:

<script>
        var myScroll;
        function loaded() {
            myScroll = new iScroll('wrapper');
        }

        document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

        /* * * * * * * *
         *
         * Use this for high compatibility (iDevice + Android)
         *
         */
        document.addEventListener('DOMContentLoaded', function () { setTimeout(loaded, 200); }, false)

</script>

The HTML:

<div id="wrapper"
         style="position:absolute;
         width:600px;
         overflow:auto;
         height: 500px;">

        <div id="scroll-content"
             style="position:absolute;
             width:600px;
             padding:0;
             height: 500px;">

              // The text that needs to be scrolled

        </div>
</div>

UPDATE: The following states that weird behavior such as rubber band effect should be fixed by changing the way iScroll is loaded. I have changed the loading as explained but I am still getting the rubber banding pinging the scrolled area back to the top when I let go.

Sometimes the DOMContentLoaded is a bit hasty and get fired when the contents are not ready. If you slip into some weird behaviors (eg: rubber band effect), try the following:

<script type="application/javascript" src="iscroll.js"></script>
<script type="text/javascript"> var myScroll; function loaded() {
    setTimeout(function () {        myScroll = new iScroll('wrapper');  },
 100); } window.addEventListener('load', loaded, false); </script>

Solution

  • Ok hopefully this will save somebody some time. The problem comes from iscroll not knowing the height of the scrollable area. This seems to happen for a number of reasons but in my case its due to some ajax calls that take place after the DOM loads.

    The solution was to refresh the iscroll var just before the scrollable area was to be displayed.

    setTimeout(function () { myScroll.refresh(); }, 0);