3

I have a select element that has the multiple attribute on it. I use javascript to move items up and down in the list.

HTML:

<select id="sel" size="10" multiple>
    <option>1</option>
    <option>2</option>
     ...
    <option>14</option>
</select>
<span id="moveDown">Move Down</span>

And the following javascript:

$("#moveDown").button().click(function () {
    var select = $("#sel");
    var selItem = $("#sel option:selected")
    var next = selItem.last().next();
    selItem.insertAfter(next);
});

The problem I have is that in Chrome and IE if the selected item is scrolled out of view, the select list does not scroll to keep the item in view. Firefox always keeps the topmost selected item in view.

If I remove the multiple attribute, then everything works as expected, but I need to be able to select multiple items for other functions of this list.

My question is, how can I scroll to the selected item? I have tried using position, offset, and height, but they are all 0 on the option in chrome:

console.log(selItem.position().top);
console.log(selItem.offset().top);
console.log(selItem.height());

Here is a fiddle that demonstrates the issue: http://jsfiddle.net/ywypB/4/

John Koerner
  • 37,428
  • 8
  • 84
  • 134
  • Interesting question, though it seems to be a Chrome bug. It returns 0 for options' offset().top, height, outerHeight and clientHeight. Nearly impossible to calculate then without throwing in arbitrary values which is terrible. Related question: http://stackoverflow.com/a/7205792/1331430 but scrollTop won't work if you can't get the option's offset though. – Fabrício Matté Mar 13 '13 at 14:32

1 Answers1

1

Very strange! Well one way to go about it is to use .scrollTop().

Why not try something like this (I know not ideal but a possible solution):

$("#moveDown").button().click(function () {
    var select = $("#sel");
    var selItem = $("#sel option:selected");
    var next = selItem.last().next();
    var index = selItem.insertAfter(next).index() + 1;
    if(index > $('#sel').attr('size')){
        $('#sel').scrollTop(17 * parseInt(index - $('#sel').attr('size'))); //17 is height of option
    }
});

DEMO: http://jsfiddle.net/dirtyd77/ywypB/16/

Dom
  • 38,906
  • 12
  • 52
  • 81
  • I am not a big fan of magic numbers, and that falls apart if the CSS changes the font size. I have been playing with tying it to the font size, but I can't quite get it working right. Also, once the items are out of their original order the index is still the original value, so it starts jumping around a lot when you move items. – John Koerner Mar 13 '13 at 20:58
  • I have changed my jsfiddle here: http://jsfiddle.net/dirtyd77/ywypB/23/ , which should fix the font-size issue. *CAUTION*: it is hacky :-/ – Dom Mar 13 '13 at 21:48