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/
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With