Ludwig Wendzich

slideTo, a smoother scrollTo with CSS3

A while back I read an article explaining how to create a smooth scroll to top with CSS transitions (via segdeha.com) and I filed that in the could be useful drawer.

Yesterday I was getting frustrated with the flashing that appeared on an iOS device when using the $.scrollTo function, and the flakiness that came along with using the $.scrollTo — I never liked how when the function is scrolling the page for you, it’s very easy to start fighting with it, if you changed your mind. Don’t get started on the amount of trouble you’re asking for if you queue up too many $.scrollTo’s. And then it hit me; that thing in that drawer could be useful.

Introducing slideTo

slideTo is very raw; I only wrote it yesterday (where I mean, I adapted this code yesterday to do something else.)

It requires jQuery and it will take either an element or an integer as it’s parameter.

function slideTo(el){
    var to = isNaN(el) ? $(el).offset().top : el, //find scroll to position
        from = $(window).scrollTop(), //find starting point
        dy = to-from, //calculate change in scroll position - deltaY
        body = $("body");

    /* We're going to use margin-top to move the the page so it feels like we're at the *from* scroll position, when we're actually instantly at the *to* scroll position. */
    
    body.css("margin-top", dy+"px");
    $(window).scrollTop(to);


    /* Now we will use CSS transitions to perform the scroll for us, by transition the margin-top to 0 */
    
    body.css("transition","margin-top 1s ease");
    body.css("margin-top", 0);


    /* Reset the transition property once we're done with it so we don't get accidental transitions, and so if we slideTo again, the first step will be instant. */
    
    body.on("webkitTransitionEnd transitionend msTransitionEnd oTransitionEnd", function(){
      $("body").css("transition", "none");
    });
}

As I said, this is all very new, and I only penned this (used liberally here, credit must go to Mahieddine Abdelkader for the original idea) yesterday. It may introduce new issues, but I haven’t discovered them yet in the limited testing I have done.