• Posted on: May 19, 2010
  • Tag: mobile dev
  • Reactions: 638

> iScroll

spacer

The 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.

spacer This script has been superseded by iScroll 4. This page is kept for historical reasons.

  • Get the Script
  • Screencast
  • Live Demo
  • Public Repo

spacer

Project info

Project state: ACTIVE (code is actively updated)
Last code update: 2010.10.08 – v3.7.1
Device compatibility: iPhone/Ipod touch >=2.0, Android >=1.5, iPad >=3.2.
Discussion Group
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.

spacer

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;
    /* your desired width, auto and 100% are fine */;
    /* 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).
  • 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 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.
  • 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 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 class="#"> 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.7.1, 2010.10.08 – Bug fix
v3.7, 2010.10.05 – Lock scrolling direction, added bounceLock and scrollbarColor options, size optimization.
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.

/Share the joy

  • Tweet

/Reactions

  • Pingback: iPhone iPadで「position: fixed」  | sloeator.com
  • Pingback: CROSSBLASTER.com | Ashes Design Weblog » フッタを下部に固定する
  • Pingback: iPhone – Scroll conteúdo com tamanho fixo (width/height) - Omugo
  • Pingback: Gotchas/bugs in development for WebKit on iOS or Android | Android JB
  • Pingback: Announcing the BerryReview PlayBook Edition Beta! - BerryReview
  • Pingback: Announcing the BerryReview PlayBook Edition Beta! | Apple/Windows/Blackberry/Android
  • Pingback: Blackberry House » Announcing the BerryReview PlayBook Edition Beta!
  • Pingback: 如何为 iPad 打造速度超快的 HTML5 软件 | 顾大侠code for yourself! no one else!
  • Pingback: Hello, iPad! | ISUX
  • Pingback: Co-Tam.design.Blog » ipadやiphoneなどwebkitブラウザでoverflow:scrollが不便
  • Pingback: HTML5 Question?: Has anyone built, or even seen, a fixed height touch friendly (iPad) web app with a 2 column design in which the two columns scroll independently? - Quora
  • Pingback: Dreamboard [Release] DreamBoard - Page 319
  • Pingback: Native style momentum scrolling to arrive in iOS 5 · Johan Brook
  • Pingback: iOS 5 (Beta 2): Safari Gains Native Scrolling, Nitro JavaScript Support | RazorianFly
  • Pingback: スマートフォン(iPhone / Android)でposition: fixedを実現する方法「iScroll.js」 — HTML5 – CSS3 mag
  • Pingback: iOS 5 Brings Native-Style Scrolling to Web Apps
  • Pingback: [jQTouch] 고정 스크롤/탭 붙이기 : 토비네
  • Pingback: iPhone用サイトを作る時の注意点 | webデザイン初心者が中級デザイナーになるためのブログ
  • Pingback: Compte rendu du séminaire Web mobile. | Phenix-factory Blog de Debondt Didier
    • Author: Matteo Spinelli
    • Posted on: 2011/07/16
    • At: 18:12

    iScroll received +850 comments and it’s becoming hard to find solutions to already asked questions.

    For this reason I set up the official iScroll Google Groups and I invite you all to send suggestions and requests there.

    Hope the iScroll group will be a helpful resource.

  • Pingback: Student, Apple Fan, Non Dualist, Feyenoord Supporter en Webdeveloper bij Webrr » Randy van Vugt
  • Pingback: 차세대를 이끌 모바일 앱 기술은? HTML5, 앱스프레소 | funnyplan.com
  • Pingback: Simulate scroll event on iPad - Programmers Goodies
  • Pingback: Team update: Week of August 22nd | jQuery Mobile
  • Pingback: iPhone position: fixed (Header/Footer/Toolbar) - Pelle Boese
  • Pingback: How can I implement a scrollable on iPad? - Programmers Goodies
  • Pingback: Jqueryでスライドボクッスをやってみた(スクロール追跡機能付き)の続き « 管理人のヒトリゴト -もみんぎゅぅ-
  • Pingback: BoredOnTrain - Andreas Hultgren
  • Pingback: ipadでoverflowとかbrのスクロールが出来ない件 | Color of Hearts
  • Pingback: Hello, iPad! | logolomo
  • Pingback: Jquery iScroll plugin | prosoxi.com
  • Pingback: flick list with its momentum scrolling and deceleration | don't code today
  • Pingback: Andrew Groat » New CSS3 Specifically For The iOS5 Update | Hybrid Web Designer & Developer
  • Pingback: flick list with its momentum scrolling and deceleration « mollybrake3
  • Pingback: Hello, iPad! | 南京UI设计
  • Pingback: Browser scrolling versus in page scrolling | SeekPHP.com
  • Pingback: Designing Web Apps for the iPad | Tips4Designer
  • Pingback: Fixing an Element and Scrolling Divs in iOS 5 « Kyle Larson Web Design Articles
  • Pingback: Pull to Refresh Javascript - Programmers Goodies
  • Pingback: AJAX and Mrs. King « Dave's Blog
gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.