Julian Jelfs’ Blog

Shrinking select lists in IE – jQuery.append bug?

Posted in jQuery by julianjelfs on March 27, 2009

I encountered a problem recently where I noticed that select lists with width set to 100% were mysteriously shrinking on me and I could only resolve the issue by setting a pixel width. This was a serious inconvenience since I have a fluid layout which is more or less ruined if I am forced to use fixed pixel widths. I found that others had noticed this issue here and here but there was no solution.

I set up a test with the following markup:

<div style=”width:300px”>

<select id=”shrinky” style=”width:100%”>

<option>One</option>

<option>Two</option>

<option>Three</option>

<option>Four</option>

<option>Five</option>

</select>

</div>


I also found, on closer examination that this seems to be a problem with using jQuery append in IE as demonstrated by the following test:

tf.AddTest(“Shrinking select list – demonstrates jquery bug”, function(test){

test.Expects(1);

var sel = $j(“#shrinky”);

var width = sel.width();

sel.append(“<option>test</option>”);

test.NotEqual(width, sel.width());

});

To show that this appears to be a problem with jQuery we can achieve the same thing manipulating the DOM manually and show that the select lists width does not change. This is demonstrated by a second test (notice the assertion at the end is flipped showing that the width is unchanged this time):

tf.AddTest(“Shrinking select list – native”, function(test){

test.Expects(1);

var sel = $j(“#shrinky”);

var width = sel.width();

var optn = document.createElement(“OPTION”);

optn.text = “test”;

sel[0].options.add(optn);

test.Equal(width, sel.width());

});

This alternative approach “solves” the problem for me in that I can still have 100% width select lists so my layout is not ruined. If I get the chance I am going to look into the way jQuery.append works to see if there is any obvious way to patch it so this alternative approach can become unnecessary.

Tagged with: ,