Last Updated: February 25, 2016
·
4.352K
· haliphax

Auto-scrolling extender for knockout.js

By extending an observableArray object, we can automatically scroll a scrollable element all the way to its bottom when that array is updated (i.e., a chat log). If the user's scroll bar isn't already at the bottom of that element, we will know that they're browsing the text, and we shouldn't interrupt them.

ko.extenders.scrollFollow = function (target, selector) {
    target.subscribe(function (newval) {
        var el = document.querySelector(selector);

        // the scroll bar is all the way down, so we know they want to follow the text
        if (el.scrollTop == el.scrollHeight - el.clientHeight) {
            // have to push our code outside of this thread since the text hasn't updated yet
            setTimeout(function () { el.scrollTop = el.scrollHeight - el.clientHeight; }, 0);
        }
    });

    return target;
};

Example usage:

var viewModel = {
    someArray: ko.observableArray().extend({ scrollFollow: '#some_element' })
};

ko.applyBindings(viewModel);

1 Response
Add your response

Here's a github gist with the source:

https://gist.github.com/haliphax/5379454

over 1 year ago ·