Reputation: 4376
I have a knockout click binding on an element. Inside of the click handler I add an element to an observableArray which is bound to a <ul>
. When an item is added to this observableArray I'd like to be able to scroll the page so that the newly-added <li>
is at the top of the page. Is there any way to do this? My thought was to get the <li>
and then use the scrollIntoView
method, but I can't figure out how to get the DOM element from the data. Seems like I need something the reverse of ko.dataFor
. Here's a JSFiddle with a TODO showing what I want: http://jsfiddle.net/klinden/rkLZ6/1/
Upvotes: 2
Views: 650
Reputation: 2314
Hope this will help:
<ul data-bind="foreach: myStuff">
<li data-bind="text: name, setFocus: {}" "></li>
</ul>
And script code:
var ctr = 2;
ko.bindingHandlers.setFocus = {
update: function(element, valueAccessor, allBindingsAccessor) {
$('html,body').animate({scrollTop: $(element).offset().top}, 500);
}
};
var vm = {
myStuff: ko.observableArray([
{name: 'foo1', desc: 'bar1'}
]),
addFooBar: function() {
this.myStuff.push({name: 'foo' + ctr, desc: 'bar' + ctr});
ctr++;
}
};
ko.applyBindings(vm);
Upvotes: 2