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);
Written by Todd
Related protips
1 Response
Here's a github gist with the source:
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Knockout.js
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#