I am working on a existing add in which we are using Knockout.js
for data binding.
One of the new requirements is to be able to automatically scroll to a specific option (determine prior by a given criteria) in the <select>
list when you cick on the button to show the dropdown
Generally if you have hardcoded <select>
list with <options>
this is pretty easy to achieve by using the scrollIntoView()
function.
The problem for me is that I noticed that all the <option>
elements created with Knockout options binding has
offsetTopproperty of 0.
Therefore
scrollIntoView()` always scroll to the top of the list.
I am wondering if there is any solution - either to manage to assign offsetTop
values to the <option>
element or some other way to scroll to specific option in the list.
I can not share the exact code , so I am giving some pseudo code:
HTML
<div id="container">
<p style="margin-top: 100px;">
Your country:
<select id="select2" data-bind="options: availableCountries,
optionsText: 'countryName',
value: selectedCountry,
optionsCaption: 'Choose...'"></select>
</p>
<div data-bind="visible: selectedCountry"> <!-- Appears when you select something -->
You have chosen a country with population
<span data-bind="text: selectedCountry() ? selectedCountry().countryPopulation : 'unknown'"></span>.
</div>
</div>
JS
var Country = function (name, population) {
this.countryName = name;
this.countryPopulation = population;
};
var viewModel = {
availableCountries: ko.observableArray([
new Country("UK", 65000000),
new Country("USA", 320000000),
new Country("Sweden", 29000000)
]),
selectedCountry: ko.observable() // Nothing selected by default
};
$(document).ready(
$('#btn').click(function () {
$('#select2').val("USA")[0].scrollIntoView();
});
ko.applyBindings(viewModel);
});
Thanks in advance