Giacomo Balli profile picture
Giacomo Balli
The Mobile Guy

Over two decades of experience at your service.
I help business owners make better decisions.

Let's Chat LinkedIn

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.

#smooth-scroll, #scroll, #javascript
Published: Mon, Jan 11 2016 @ 11:39:35
Back to Blog