Giacomo Balli profile picture
Giacomo Balli
Complex decisions. Clear thinking.

Independent advice for business owners navigating technology decisions, challenges and opportunities.
Fluent in business. Grounded in technology. Paid only by you.

Let’s Talk It Through LinkedIn

Building technology products since 2010 · 100+ apps

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: Fri, Apr 23 2021 @ 15:22:25
Back to Blog