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 aposition: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 addingpreventDefault() 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 tofalse by default.
  • bounce: set to false to prevent the scroller to bounce outside of boundaries (Android behavior). Defaulttrue (iPhone behavior).
  • bounceLock:, if set to true the scroller stops bouncing if the content is smaller than the visible area. Default: false (as per native iphone scroll).
  • 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 falseand 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.
  • scrollbarColor: changes the color of the scrollbar. It accepts any valid CSS color (default:'rgba(0,0,0,0.5)'

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 isnot 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 withcheckDOMChanges: 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 thehScrollbar: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?

Leave a comment