jessikwa jessikwa - 7 months ago 24
HTML Question

Scrolling select element jumps to top when removing options from DOM in IE

This issue appears to be isolated to Internet Explorer:

I'm moving

option
tags from one
select
to another when they're double clicked using Javascript. The
select
elements can have many items, so I've set the height with
overflow: auto;
so that they scroll. If you scroll down the list and double click an item to move, the
select
list will scroll up to the top when the
option
is removed, instead of staying at the current scrolled-to position as it does in Chrome or Firefox.

I made a basic example to demonstrate this here: https://jsfiddle.net/yk8LeLbw/1/

The Javascript is pretty simple:

$(".listBoxSelectorAvail").dblclick(function() {
$(this).find("option:selected").remove().appendTo(".listBoxSelectorAssigned");
});
$(".listBoxSelectorAssigned").dblclick(function() {
$(this).find("option:selected").remove().appendTo(".listBoxSelectorAvail");
});


I haven't been able to find any specific reason why this happens - I'm not sure if it's a bug or if this is expected behavior, but is there anything that can be done?

EDIT: made the title more clear

EDIT 2: I was hoping to stop the scrolling, but the best solution I've come up so far is to rescroll once the item has been moved, as seen here:
https://jsfiddle.net/yk8LeLbw/2/

Answer

The issue is that IE behaves differently. So, we have to work around that unwanted behavior. The solution is to wrap the select in a div and use some CSS.

Here's a working jsFiddle.

Note how I wrapped a div around each select and replaced the size="50" attribute with the multiple="true" attribute. This removes the scrollbar on the select elements.

$(document).ready(function() {
  var arr1 = [];
  var arr2 = [];
  arr1.push("<div class='scroll'><select class='listBoxSelectorAvail' multiple='true'>");
  arr2.push("<div class='scroll'><select class='listBoxSelectorAssigned' multiple='true'>");
  for (var i = 0; i < 20; i++) {
    arr1.push("<option value=\"" + i + "\">Option " + i + "</option>");
  }
  arr1.push("</select></div>");
  arr2.push("</select></div>");
  $("body").append(arr1.join(""));
  $("body").append(arr2.join(""));
  $(".listBoxSelectorAvail").dblclick(function(e) {
    $(this).find("option:selected").remove().appendTo(".listBoxSelectorAssigned");
  });
  $(".listBoxSelectorAssigned").dblclick(function(e) {
    $(this).find("option:selected").remove().appendTo(".listBoxSelectorAvail");
  });
});

Here's the modified CSS.

select {
  width: 200px;
  height: 200px;
}
.scroll {
  overflow: auto;
  display: inline-block;
  margin-left: 10px;
}
Comments