iScroll v3The overflow:scroll for mobile webkit. Project started because webkit for iPhone does not provide a native way to scroll content inside a fixed size (width/height) div. So basically it was impossible to have a fixed header/footer and a scrolling central area. Until now.
May 2010
19
Replies
332


Project info

Project state: ACTIVE (code is actively updated)
Last code update: 2010.08.24 – v3.6
Device compatibility: iPhone/Ipod touch >=2.0, Android >=1.5, iPad >=3.2.
QR Code opens demo page.

Support development

If this script saved your day or you wish to support iScroll and other scripts development you may consider sending some funds via PayPal.


Overview

iScroll was born because mobile webkit (on iPhone, iPod, Android and Pre) does not provide a native way to scroll content inside a fixed width/height element. This unfortunate situation prevents any web-app to have a position:absolute header and/or footer and a scrolling central area for contents.

Luckily mobile webkit offers a powerful set of hardware accelerated CSS properties that can be used to simulate the missing functionality, so the iScroll development started… But there’s no rose without thorn. Making the scroll feel native has proven more difficult than expected.

How to use

First of all we need to prevent the default behavior of standard touch events. This is easily done adding preventDefault() to the touchmove event. Then initialize the iScroll object on DOMContentLoaded or on window load. Here an example:

function loaded() {
	document.addEventListener('touchmove', function(e){ e.preventDefault(); });
	myScroll = new iScroll('scroller');
}
document.addEventListener('DOMContentLoaded', loaded);

iScroll takes two parameters. The first is mandatory and is the ID of the element you want to scroll. The second is optional and can be used to pass additional parameters (see below).

On the HTML/CSS side the scrolling area needs to be wrapped by an element which determines the scroller actual size. The following is a common tags configuration for an iScroll.

<div id="wrapper">
    <div id="scroller">
        <ul>
            <li>...</li>
        </ul>
    </div>
</div>

The #wrapper also needs some classes:

#wrapper {
    position:relative;
    z-index:1;
    width:/* your desired width, auto and 100% are fine */;
    height:/* element height */;
    overflow:/* hidden|auto|scroll */;
}

That’s it. Enjoy your scrolling. Have a look at the source code of the online example to get a better idea of how the iScroll works.

Syntax

The iScroll syntax is: iScroll(mixed element_id, object options).

element_id, can be both an object pointing to or a string with the ID name of the element to be scrolled. Example: iScroll(document.getElementsByTagName('div')[1]) or iScroll('scroller')

Accepted options are:

  • hScrollbar: set to false to never show the horizontal scrollbar. The default value true makes the iScroll smartly decide when the scrollbar is needed. Note that if device does not support translate3d hScrollbar is set to false by default.
  • vScrollbar: set to false to never show the vertical bar. The default value true makes the iScroll smartly decide when the scrollbar is needed. Note that if device does not support translate3d vScrollbar is set to false by default.
  • bounce: set to false to prevent the scroller to bounce outside of boundaries (Android behavior). Default true (iPhone behavior).
  • checkDOMChanges: set to false to prevent auto refresh on DOM changes. If you switch off this feature you have to call iScroll.refresh() function programmatically every time the DOM gets modified. If your code makes many subsequent DOM modifications it is suggested to set checkDOMChanges to false and to refresh the iScroll only once (ie: when all changes have been done). Default true.
  • fadeScrollbar: define wether the scrollbars should fade in/out. Default true on iPhone, false on Android. Set to false for better performance.
  • momentum: set to false to remove the deceleration effect on swipe. Default true on devices that support translate3d.
  • shrinkScrollbar: set to false to remove the shrinking scrollbars when content is dragged over the boundaries. Default true on iPhone, false on Android. It has no impact on performances.
  • desktopCompatibility: for debug purpose you can set this to true to have the script behave on desktop webkit (Safari and Chrome) as it were a touch enabled device.
  • snap: set to true to activate snap scroll.

Note: options must be sent as object not string. Eg:

myScroll = new iScroll(’scroller’, { checkDOMChanges: false, bounce: false, momentum: false });

Snap scroll

When calling iScroll with “snap” option the scrolling area is subdivided into pages and whenever you swipe the scroll position will always snap to the page. Have a look at the screencast to get an idea.

Probably the best way to use “snap” is by calling it without momentum and scrollbars:

new iScroll('scroller', { snap:true, momentum:false, hScrollbar:false, vScrollbar:false });

If you keep momentum, you get a free-scrolling that will always stop to prefixed positions.

To have a perfect snapping experience the scrolling area should be perfectly divisible by the container size. Eg: If the container width is 200px and you have 10 elements, the whole scroller should be 2000px wide. This is not mandatory as iScroll doesn’t break if the last page is smaller than the container.

Methods

  • refresh(): updates all iScroll variables. Useful when the content of the page doesn’t scroll and just “jumps back”. Call refresh() inside a zero setTimeout. Eg: setTimeout(function () { myScroll.refresh() }, 0).
  • scrollTo(x, y, timeout): scrolls to any x,y location inside the scrolling area.
  • scrollToElement(el, runtime): scrolls to any element inside the scrolling area. el must be a CSS3 selector. Eg: scrollToElement("#elementID", '400ms').
  • scrollToPage(pageX, pageY, runtime): if snap option is active, scrolls to any page. pageX and pageY can be an integer or prev/next. Two keywords that snap to previous or next page in the raw. The “carousel” example in the zip file is a good starting point on using the snap feature.
  • destroy(full): completely unloads the iScroll. If called with full set to true, the scroller is also removed from the DOM.

Best practices

DOM Changes – If scrolling doesn’t work after an ajax call and DOM change, try to initialize iScroll with checkDOMChanges: false and call refresh() function once the DOM modifications have been done. If this still doesn’t work try to put refresh() inside a 0ms setTimeout. Eg:

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

Performance – CSS animations are heavy on the small device CPU. When too many elements are loaded into the scrolling area expect choppy animation. Try to reduce the number of tags inside the scrolling area to the minimum. Try to use just ULs for lists and Ps for paragraphs. Remember that you don’t actually need an anchor to create a button or send an action, so <li><a href="#" onclick="..." />text</a></li> is a waste of tags. You could remove the anchor and place the click event directly on the LI tag.

Try to avoid box-shadow and CSS gradients (especially on Android). I know they are cool and classy, but they don’t play well with CSS animations. Webkit on iPhone seems to handle shadows and gradients a bit better than its counterpart on Android, so you may selectively add/remove features based on the device.

Use a flat color for the #wrapper background, images in the scroller wrapper once again reduce performance.

Important: to preserve resources on devices that don’t support translate3d (namely: Android<2.0) iScroll disables momentum, scrollbars and bounce. You can however reactivate them using the respective options.

Bugs and limitations

Form fields do not play well with CSS animations. Countermeasures have to be adopted on a case-by-case basis.

Please use the issue tracker on Google Code to submit a bug report. You can also follow day by day updates on Google Code.

Future developments

  • I’m considering Palm Pre compatibility.
  • Check for multiple consecutive changes to the DOM to prevent unnecessary calls to the refresh() function.
  • Maybe we can achive better performances with lazy loading and pre-fetching. Lazy loading takes care of loading and unloading elements when they are not needed (ie: out of the screen). Pre-fetching can be used to preload all elements to reduce flickering.

FAQ

Q: Why on Android 1.5/1.6 I’m not seeing the scrollbars?
A: On older devices iScroll disables the scrollbars and other effects. You can reactivate them passing the hScrollbar:true and/or vScrollbar:true options.

Q: Why aren’t you adding feature X?
A: I’d like to keep the iScroll as bare-bone as possible, before adding a new feature I carefully estimate the pros and the cons.

Q: I’ve developed feature X, may I send it to you?
A: Please do! It’s not guaranteed that I will add your feature to the script, but I review all code you send to me.

Q: I’m in a hurry and I need feature X to be added to your script ASAP. Can you help me?
A: Have you considered hiring me?

Revisions history

v3.6, 2010.08.24 – Bug Squashing Edition.
v3.6 beta 1, 2010.08.10 – Added snap scroll.
v3.5.1, 2010.07.30 – Mandatory bug fix.
v3.5, 2010.07.27 – Added scrollToElement() method, fixed a bug with scrollbars and multiple iScroll instances, a bit of code clean up.
v3.4.5, 2010.07.04 – Prevent JS error on browsers not supporting WebKitCSSMatrix.
v3.4.4, 2010.06.30 – Better orientation detection.
v3.4.3, 2010.06.27 – Bug fix.
v3.4.2, 2010.06.24 – Bug fix.
v3.4.1, 2010.06.24 – Enhanced shrinking scrollbars.
v3.4, 2010.06.20 – Shrinking scrollbars and preliminary desktop compatibility.
v3.3, 2010.06.11 – Code freeze, let’s go for 3.4.
v3.3 beta 3, 2010.06.10 – Full (?!) Android compatibility.
v3.3 beta 2, 2010.06.08 – Better Android compatibility.
v3.3 beta 1, 2010.06.04 – Added Android >=1.5 compatibility.
v3.2.1, 2010.06.03 – Bug fix.
v3.2, 2010.05.31 – Code clean up.
v3.1 beta 1, 2010.05.06 – Added auto refresh on DOM changes.
v3.0 alpha 1, 2009.11.30 – Complete code rewrite. Scrollbars added. Optimized deceleration.
v2.3, 2009.07.09 – translate() replaced by translate3d().
v2.2, 2009.06.18 – Added OS3.0 compatibility.
v2.1, 2009.02.12 – Added refresh() function.
v2.0, 2009.02.03 – Optimized deceleration formula.
v1.1, 2009.01.18 – Removed timers.
v1.0, 2009.01.03 – Initial release.

Reactions

  1. pingback links for 2010-08-16 « Gatunogatuno’s Weblog2010/08/16 at 11:05
  2. homer2010/08/16 at 16:18
    Reply

    Really tidy. Great work.

     
  3. John2010/08/17 at 04:05
    Reply

    For the love of god please someone reply with advice to my problem:

    When I scroll past the initial height of the page, I lose cut/copy/paste and selection of text in text fields on the iPhone.

    Is this supposed to happen?

     
  4. Frode Helland2010/08/18 at 15:23
    Reply

    There is a problem with text rendering. I’m on an iPad, and the font in question is Georgia, so hinting is not the problem. I assume the Quartz rendering can’t keep up when text doesn’t fall on full pixels.

     
  5. Rene2010/08/20 at 11:30
    Reply

    I love this script. I’ve two issues though.

    The scrolling doesn’t work when using “display: -webkit-box” to automatically calculate the height of the wrapper div. This is useful because you don’t need to set the height of the scrolling div explicitly. It is calculated for you by the browser. It automatically adjusts the height in full screen mode when there is no mobile safari button bar at the bottom.

    Another issue is that I cannot scroll to the end of the content. When I try to scroll the last page it jumps back to the previous page. When I set bounce to false I cannot scroll the last page at all. Is there a work-around?

     
    • Matteo Spinelli2010/08/20 at 14:48

      regarding the -webkit-box issue there’s little I can do about it, sorry. Anyway I’d need to see your code, there’s probably some CSS problem.

       
    • Rene2010/08/24 at 11:02

      Sometimes I can scroll to the bottom and sometimes not.

      The code is here:

      http://latolato.com/iswp/

       
    • Rene2010/08/27 at 11:13

      I’ve solved the problem.
      The problem was that the initialization was done on DOMContentLoaded. Now I do it onload. It seems that iScroll doesn’t calculate the right scrolling height when just the DOM-tree is loaded.

       
  6. Adam Magaluk2010/08/20 at 15:25
    Reply

    I love the script by the way.

    However I am having trouble when I want to use the 2 different scroll areas on two separate Jquery tabs.

    The first tabs scroll area always works but when I click the tab to go to the next scroll area it does not work. In a regular browser I can see the scroll bars but on the Ipad the javascript isnt working.

    Ive tried creating two iScroll instances as shown:

    var myScroll;
    var myScroll2;

    function loaded() {

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

    myScroll = new iScroll(‘scroller’);
    myScroll2 = new iScroll(‘scroller2′);

    }

    document.addEventListener(‘DOMContentLoaded’, loaded, false);

    Then further down in the HTML I have two wrappers and two scrollers named differently.

    Any help would be much appreciated.

     
    • Matteo Spinelli2010/08/20 at 16:08

      try to myScroll2.refresh() when you click on the second tab.

       
  7. pingback slablet — award tour2010/08/20 at 16:22
  8. Adam Magaluk2010/08/20 at 16:25
    Reply

    That didn’t work.

    However I figured it out.

    You have to add the Jquery tab stuff in the loaded function after you declare the iScroll variables. Im not sure why but it works.

    My loaded function looks like:

    function loaded() {

    document.addEventListener(‘touchmove’, function(e){ e.preventDefault(); }, false);
    myScroll = new iScroll(‘scroller’);
    myScroll2 = new iScroll(‘scroller2′);

    $(function() {
    $(“#audioSubTab”).tabs({
    ajaxOptions: {
    error: function(xhr, status, index, anchor) {

    $(anchor.hash).html(“Couldn’t load this tab. We’ll try to fix this as soon as possible. If this wouldn’t be a demo.”);
    }
    }
    });
    });

    }

     
  9. Adrian von Gegerfelt2010/08/23 at 18:39
    Reply

    iScroll is the best thing ever! Works like a charm on an iPad (though I can’t get the bounce or the momentum to work. I’m hoping to having smooth scrolls on both axis on the same page ^_^

    Cheers!

     
  10. Cole2010/08/23 at 23:49
    Reply

    I’m having an issue with multiple scrolling blocks on a single page on the iPad. is anyone else finding this problem?

    The first block behaves as expected, however additional blocks all align themselves in the top left corner as soon as iScroll loads. prior to loading they are all positioned correctly.

     
  11. Pram2010/08/24 at 10:52
    Reply

    Hei Matteo!, Good job!

    btw, I have a case like this : I have some elements inside the scrolling li (list) and that elements have to be clickable .
    Before I equip with iScroll, it got clickable nicely, but after I equipped with iScroll it got unable to click.

    Would you lend me some a hand ?

    Thx, Pram

     
  12. Claudio Cicali2010/08/24 at 11:21
    Reply

    Hi Matteo, it’s me again :) Just wondering why you trap (and then kill) the “click” event if (!isTouch). I can’t figure out the reason and it interferes with my tests with chrome or firefox. I have to comment it out, w/o side effects (it seems).

    Thank you

     
    • Matteo Spinelli2010/08/24 at 12:08

      I’m in bug hunting session right now. I’ll be releasing a new version in a couple of hours. I’ll look into the click event thing, too. Please check back later.

       
    • Matteo Spinelli2010/08/24 at 20:47

      this should be fixed

       
  13. Marwan2010/08/24 at 12:28
    Reply

    Great job, congratulation

     
  14. Pram2010/08/24 at 13:31
    Reply

    Hi Matteo,
    thanx for your corresponding ..
    And for Claudio’s action for this problem, it seems to be alright to commented out that code lines ..

    kind regards,
    Pram

     
  15. Marwan2010/08/24 at 14:02
    Reply

    Hi Matteo,
    how I can fixe the “float” css bounces back issue?

    Best regards

     
  16. Adrian von Gegerfelt2010/08/24 at 18:46
    Reply

    On an iPad, If I want to load/embed a PDF file into a div, or an iframe or as an embed tag, what is the best practice?

    I don’t know how to make an iframe scrollable with iScroll, for instance :/

     
  17. Brian2010/08/24 at 21:19
    Reply

    Does anyone know how this compares with “Pastry-Kit” library and Sencha libraries that implement this type of scrolling? I haven’t actually looked into those at all but wondering if any of you had?

     
  18. jujunosuke2010/08/25 at 09:09
    Reply

    Hello, when developping web app for iphone, we can get rid of the search bar at the top with

    window.scrollTo(0, 1);

    But it looks like it doesn’t work with iScroll..
    any idea for that ?

    Thanks

     
    • Matteo Spinelli2010/08/25 at 10:11

      I’d need to add this to the FAQ. The page height must be higher than the visible screen for the URL bar to hide (try adding a padding-bottom to the body, you’ll see what I mean).

       
  19. jujunosuke2010/08/25 at 11:13
    Reply

    How, yes sorry, i just get the answer by reading some message.

    In my first message i forget to thank you for the very very great work.
    Good Job Matteo, The result is amazing.
    I can get Fixed position perfect for iPhone, android + page sliding translateX + other cool features.

     
  20. Carl2010/08/25 at 17:22
    Reply

    Hi, I’m using iscroll for both iPhone and Android. It works correctly in my application on iPhone and Android 2.0-2.1, but I have a problem with Android 2.2. If I have an text input field in the scrolling area I can’t give it focus by clicking it. Is this a known problem with iscroll? If, what kind of workarounds are possible?

    /Carl

     
    • Carl2010/08/25 at 17:35

      I managed to fix it by using this:
      $(‘#myInput’).bind(‘touchstart’, function(e) {
      e.stopPropagation();
      });

       
  21. mark2010/08/30 at 05:43
    Reply

    How do I get this to work with an image? I want an image in a div to be scrollable, but no matter what markup/css I use the image just bounces around. I’ve read in comments about setting explicit image heights/widths. Can you elaborate? Can you provide an example with markup and css?

     
    • Matteo Spinelli2010/08/30 at 11:17

      <img src=”…” width=”100″ height=”100″ alt=”image” />

      that’s all

       
  22. Fabio Galdo2010/08/30 at 20:54
    Reply

    do you plan to port this to a jquery-friendly version?

     
    • Matteo Spinelli2010/08/30 at 22:44

      This is already compatible with jquery, making a plugin out of it would make it slower.

       
  23. John2010/08/31 at 05:46
    Reply

    The latest version (3.6) is not refreshing the iscroll on dynamic changes anymore. Previous version was fine. What was changed now that it is no longer working for me?

     
    • Matteo Spinelli2010/08/31 at 09:12

      Thanks for your report. I’ll check it out. On google code you can get full diff if you want to revert.

       
  24. kyel2010/08/31 at 18:30
    Reply

    Awesome Work!
    Probably right in front of me, but I can’t find the ‘custom-scrollbar example’ you refer to in the main http://cubiq.org/iscroll page (under available options > scrollbarClass).
    Thanks!

     
    • Matteo Spinelli2010/08/31 at 19:44

      you are totally right, forgot to remove the “scrollbarClass” parameter from the docs. I had to remove it in one of the latest release.

       
  25. Sasho2010/09/01 at 12:56
    Reply

    Hi, i make a web app in ASP.Net MVC, in one main page i have 4 partials(views) with 5 lists. I have 5 instances of iScroll, the scrolls work very well on Android but
    on iPhone nothing happens.

    First, how it works.
    At first i can’t make 5 instance of the iScroll so i
    make a little changes to the script:

    - Wrap the script with my object
    MobileScroll = function() {
    divId:null;
    }
    - function to initialize the script for
    current scroll
    MobileScroll.prototype.initScroll = function() {
    {isScroll script}
    }

    // how looks in action
    cutomListScroll = new MobileScroll();
    cutomListScroll.divId = $(“#wraper”);
    cutomListScroll.initScroll();
    cutomListScroll = new iScroll(“scroller”);

    workoutListScroll = new MobileScroll();
    workoutListScroll.divId = $(“#workoutsHolder”);
    workoutListScroll.initScroll();
    workoutListScroll = new iScroll(“workoutScroller”);
    …. other 3 scroll objects

    Maybe i make some mistakes or this is not right way how i do this, please for some help.

     
    • Matteo Spinelli2010/09/01 at 13:05

      why not something like:

      var myScroll = [];
      var wrappers = document.querySelectorAll('.wrapper');
      
      for (var i=0; i<wrappers.length; i++) {
      	myScroll[myScroll.length] = new iScroll(wrappers[i], ...);
      }
      

      of course the wrappers must have class “wrappers”.

       
  26. Devin2010/09/01 at 22:14
    Reply

    I seem to have an issue with the keyboard not showing up when clicking on an input box that is nested in a table. If I pull the input out it works fine. This is an issue with a droid x. It works fine on my iPhone 3GS. Any ideas???

    Thanks

     
  27. Robbin2010/09/02 at 11:28
    Reply

    I seem to not being able to click on an iOS 2 device. It seems like that.moved gets value true all the time, and preventing clicks.

    In function touchStart, there is this code:

    1 – // Check if the scroller is really where it should be
    2 – if (that.options.momentum || that.options.snap) {
    3 – matrix = new WebKitCSSMatrix(window.getComputedStyle(that.element).webkitTransform);
    4 – if (matrix.e != that.x || matrix.f != that.y) {
    5 – document.removeEventListener(‘webkitTransitionEnd’, that, false);
    6 – that.setPosition(matrix.e, matrix.f);
    7 – that.moved = true;
    8 – }
    9 – }

    Inserting an alert between line #3 and #4:

    alert(matrix.e+’ , ‘+matrix.f+’\n’+that.x+’ , ‘+that.y+’\n’+window.getComputedStyle(that.element).webkitTransform);

    This gives the following alertbox on iOS2:

    undefined, undefined
    0, 0
    matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)

    … and this on iOS3:

    0, 0
    0, 0
    matrix(1, 0, 0, 1, 0, 0)

     
    • Matteo Spinelli2010/09/02 at 12:03

      iOS2… wow this is ancient :) Don’t have a 2.x device at hand to test with. Try to send me the result of:

      for (var i in matrix) {
       console.log(i + ': ' + matrix[i]);
      }
       
    • Robbin2010/09/02 at 12:41

      Yeah, I know. I just want to support it too, so I always keep my old 1st gen iPod Touch without upgrading it.

      Result (first value i output is if unscrolled, second is if scrolled 72px horizontally (swipe left).

      m13: 0 , 0
      m12: 0 , 0
      m11: 1 , 1
      m42: 0 , 0
      m41: 0 , -72
      m23: 0 , 0
      m24: 0 , 0
      m31: 0 , 0
      m32: 0 , 0
      m43: 0 , 0
      m21: 0 , 0
      m14: 0 , 0
      m22: 1 , 1
      m34: 0 , 0
      m33: 0 , 1
      m44: 0 , 1

      The rest of the elements inside are native functions: scale(), rotate(), translate(), rotateAxisAngle(), inverse(), multiply(), setMatrixValue() and toString()

      So it seems like m41 contains the x value. My iScroll only scrolls horizontally, but I will adjust and come back with what attribute is active for the y value as well.

       
    • Robbin2010/09/02 at 13:00

      Scrolling 72 pixels horizontally instead (swipe upwards), changes m42 to value -72, other values unchanged.

      The exact same applies to iOS 4, and iPad with iOS 3.2, by the way. Haven’t had time to test these values on an Android device yet.

       
  28. Seungjin Im2010/09/03 at 13:49
    Reply

    Snap option is active, wrapper div`s width is 300%,
    and inner div`s width is 100% (three divs).
    in this situation, I set all inner div`s height in varying each other.

    First inner div has 2 pages (as a result of snap option)
    and second inner div has 1 page,
    When I scrolling page 2 and swiping right, (toward second div)
    Just displaying empty background..

    I want displaying second`s page 1 correctly, when I swiping toward structural empty place

     

Speak your mind