Posts Tagged ‘JavaScript’


Internet Explorer select (dropdown list) width fix

May 27, 2011

I recently stumbled upon one of the Internet Explorer’s many pitfalls.. again.
If you have created a wide variety of websites you probably have encountered this problem, too.
Upon setting a fixed width for a HTML dropdown box that i.e. is displayed in a floating sidebar next to your main content you may notice that the options do not expand to the necessary width to present the content to the end use – it will just be cut off in Internet Explorer (not so in Firefox).

You have several options and searching the web for a possible solution will bring up tons of possible solutions. My first guess before doing any search was to set the width of the <option> elements to auto – guess what? Doesn’t work either, yay!

So I came up with a JavaScript solution that depends on jQuery, but can be adapted to be used without it I guess, though I do love jQuery and I do not see any reason not to rely on it.
The trick is basically to alter the width of the <select> element whenever the user opens it, so IE will auto size the dropdown list to the appropiate width.

Here’s my code which I adapted from this post on stackoverflow:

if ($.browser.msie && $.browser.version < 9)
.bind('focus mouseover', function() { $(this).addClass('expand').removeClass('clicked'); })
.bind('click', function() { if ($(this).hasClass('clicked')) { $(this).blur(); } $(this).toggleClass('clicked'); })
.bind('mouseout', function() { if (!$(this).hasClass('clicked')) { $(this).removeClass('expand'); }})
.bind('blur', function() { $(this).removeClass('expand clicked'); });

In your stylesheet you put these lines:

select.width-fix {
width: 200px; /* Just an example for a fixed width. */
z-index: 1000; /* Make sure to put the select and its options above all other HTML elements. */

select.expand {
width: auto; /* Let the browser handle it. */

In your HTML code:

<select class="width-fix">
... [options here]

I hope this helps somebody else, too. I have tested this piece of code with IE8/7 successfully.. I do not care for IE6 anymore.

Happy Coding!