Custom Scrolling With Meteor

I’ve recently tried using Meteor to build a web application.
I used Iron.Router to configure the different routes of the web application. Everything worked fine out of the box until I started using links with fragment identifiers.

First thing I wanted to add was an animated scroll behavior when navigating between anchors on the same page.
I was able to achieve this by overriding the scrollToHash-function:

(animated-scroll.js) download
1
2
3
4
5
6
7
8
9
Router._scrollToHash = function (hash) {
    var section = $(hash);
    if (section.length) {
        var sectionTop = section.offset().top;
        $("html, body").animate({
            scrollTop: sectionTop
        }, "slow");
    }
};

Next I noticed that when scrolling in a page and then navigating to a new one, the scroll remained at its last position.
The user experience was not acceptable. When navigating to a new page, the user expects to land on top of the page and not somewhere in the middle.

To fix this behavior I used the Iron.Router hooks. I added a global hook that scrolls to the top of the page after the routing.
This can be achieved by adding the following code:

(scroll-to-top.js) download
1
2
3
4
5
6
7
var IR_AfterHooks = {
    scrollUp: function() {
        $('body,html').scrollTop(0);
    }
};

Router.onAfterAction(IR_AfterHooks.scrollUp);

With these two customizations I was able to have a nice scrolling user experience with my meteor application.
What about you, do you have interesting customization to share ?

Comments