Giacomo Balli profile picture
Giacomo Balli
Innovation consultant specializing in mobile strategy
Let's Chat

Smooth scroll


This code sample will allow you to scroll the view to a predefined vertical offset (in pixels) or the beginning of a specified id.


function smoothScroll(y) {
if (typeof y === "string") {y=document.querySelector("#"+y);}
if(typeof y === "object") {y=y.offsetTop;}
for (var i = 0; i < y; i++) {
setTimeout(function () {
document.body.scrollTop = arguments[0] * 2;
}, i * 2, i);
}
}

Directions:

- Call smoothScroll(y);

- y can be a number (offset from top in pixels) or a string identifying an id.


Note:
This snippet focuses on iOS development. Make sure to verify/adapt any vendor prefixes.

Back to main listing.

Published: Mon, 11 Jan 2016 19:39:35 +0000