JSFiddle - React, Tailwind, and code Playground
HTML
<select size="5" name="selectMultiple" multiple="multiple" style="width:100%; overflow-y: scroll;" id="mySelector">
<option value="0">line 0</option>
<option value="1">line 1</option>
<option value="2">line 2</option>
<option value="3">line 3</option>
<option value="4">line 4</option>
<option value="5">line 5</option>
<option value="6">line 6</option>
<option value="7">line 7</option>
<option value="8">line 8</option>
<option value="9">line 9</option>
<option value="10">line 10</option>
<option value="11">line 11</option>
<option value="12">line 12</option>
</select>
JavaScript
// Get the selector element
var mySelectorObj = $('#mySelector');
var mySelector = mySelectorObj[0];
// If the selector is doomed to glitch out on us because it's wider than the max allowed width, we need to fix it
if (mySelector.offsetWidth > 13 * mySelector.options.length) {
// Figure out the pixels for a single scroll line
mySelector.scrollByLines(1);
var scrollLineHeight = mySelector.scrollTop;
// Scroll back to the top
mySelector.scrollTop = 0;
// Add a keydown event listener so that we can scroll programatically before it messes up
mySelectorObj.on('keydown', function(e) {
// Only listen to up and down arrows
if (e.keyCode !== 38 && e.keyCode !== 40) {
return;
}
// Figure out where the selector is scrolled to
var scrollTop = this.scrollTop;
var scrolledToLine = parseInt(scrollTop / scrollLineHeight);
// If we hit the up arrow and the selected index is equal to the scrolled line, simply move us up by one
if (e.keyCode === 38 && this.selectedIndex === scrolledToLine) {
this.scrollByLines(-1);
}
// If we hit the down arrow and the selected index is equal to the scrolled line + the number of visible lines - 1, move us down by one
if (e.keyCode === 40 && this.selectedIndex === scrolledToLine + (this.size - 1)) {
this.scrollByLines(1);
}
});
}