I am trying to find a way of scrolling to a list item (or anything for that matter) in KnockoutJS.
All I have is an object/id from a list, to which I wish to scroll.
I have put-together a functioning (and simplified) version of what I am trying to achieve below.
Demo: http://jsfiddle.net/qczdvkat/
JavaScript:
function ViewModel()
{
var self = this;
self.items = ko.observableArray([]);
for(i = 0 ;i < 150; i++)
{
self.items.push({id: i, title: 'Item No. ' + i});
}
self.scrollToItem = function() {
console.log('Scrolling to item 125...');
$('ul').scrollTop($('ul [data-id="' + 125 + '"]').position().top - $('ul li:first').position().top);
};
}
$(function() {
ko.applyBindings(new ViewModel());
});
HTML:
<ul data-bind="foreach: items">
<li data-bind="text: title, attr: {'data-id': id}">
</li>
</ul>
<button data-bind="click: scrollToItem">Scroll to Item No. 125</button>
CSS:
ul
{
max-height: 150px;
overflow-y: scroll;
border: 1px solid #000;
}
While the above works, I am looking for a way that is cleaner/more KnockoutJS and which does not involve the jQuery/data-* attributes which I am employing - since it works against the MVVM principles.
I suppose the root of the question boils down to: how to I get a DOM-element from a specific object inside a rendered list/tree/etc.?
While I have found a few resources here on StackOverflow, none solved this particular issue from what I saw.