Steve Chambers Steve Chambers - 1 year ago 77
HTML Question

How to scroll current dropdown list position up or down by a specified number of items?

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>

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...

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download