0

Given a dropdown list with many items:

<select id="selectId">
    <option value="1">Item #1</option>
    <option value="2">Item #2</option>
    ...
    <option value="100">Item #100</option>
</select>

I'm wondering how to write a jQuery function to scroll up/down by a specified number of items.

Note: There are similar SO questions for scrolling to a specified element but how would I know which element this is? All that should be passed in the function interface is the number of elements to scroll up or down from the current scroll position...

Steve Chambers
  • 37,270
  • 24
  • 156
  • 208

1 Answers1

0

This would be fairly easy if it were possible to find out the height of each <option> in the <select>. However, it seems this isn't trivial (e.g. see here). Best I could come up with is the following:

function scrollUp($select, numOptions) {
    // Assuming default of 8 visible options in select without a 'size' attribute
    var selectSize = $select.attr('size') || 8;
    // Option height calculated below - may not be completely accurate?
    var approxOptionHeight = Math.floor($select.height() / selectSize);
    var newScrollTop = $select.scrollTop() - (numOptions * approxOptionHeight);
    if (newScrollTop < 0) {
        newScrollTop = 0;
    }
    $select.scrollTop(newScrollTop);
}
Community
  • 1
  • 1
Steve Chambers
  • 37,270
  • 24
  • 156
  • 208