Skip to content

Instantly share code, notes, and snippets.

@goblindegook
Created August 25, 2010 16:19
Show Gist options
  • Save goblindegook/549794 to your computer and use it in GitHub Desktop.
Save goblindegook/549794 to your computer and use it in GitHub Desktop.
Select box auto-width workaround for Internet Explorer (requires jQuery)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Select auto-width workaround for Internet Explorer</title>
<link rel="stylesheet" type="text/css" href="select-autowidth.css" title="Select Autowidth" />
<script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script>
<!--[if IE]>
<script src="select-autowidth.js" type="text/javascript"></script>
<![endif]-->
</head>
<body>
<h1>Auto-width</h1>
<div>
<select class="autowidth">
<option>Lorem ipsum dolor sit amet, consectetur adipiscing elit</option>
<option>Lorem ipsum dolor sit amet, consectetur adipiscing elit</option>
</select>
</div>
<h1>No auto-width</h1>
<div>
<select>
<option>Lorem ipsum dolor sit amet, consectetur adipiscing elit</option>
<option>Lorem ipsum dolor sit amet, consectetur adipiscing elit</option>
</select>
</div>
</body>
</html>
select.autowidth {
width: 200px; /* change this */
}
select.autowidth.autowidth-expand {
width: auto;
z-index: 9999;
position: absolute;
}
$(document).ready(function() {
$('select.autowidth')
.bind('click', function () {
$(this).toggleClass('autowidth-clicked');
} )
.bind('focus mouseover', function () {
// In some cases, dummy SELECT may prevent container from resizing on z-index change:
// $(this).after( $('<select><option/></select>').addClass('autowidth-dummy').css('visibility', 'hidden') );
$(this).addClass('autowidth-expand');
$(this).removeClass('autowidth-clicked');
} )
.bind('mouseout', function () {
if (!$(this).hasClass('autowidth-clicked')) {
$(this).removeClass('autowidth-expand');
// In some cases, dummy SELECT may prevent container from resizing on z-index change:
// $(this).next('.autowidth-dummy').remove();
}
} )
.bind('blur', function () {
$(this).removeClass('autowidth-expand autowidth-clicked');
// In some cases, dummy SELECT may prevent container from resizing on z-index change:
// $(this).next('.autowidth-dummy').remove();
} );
} );
@PowerKiKi
Copy link

Hi,

You might be interested in a fully fledged jQuery plugin to solve this problem. It supports non-breaking layout and keyboard interactions. And does not require to modify HTML markup. check out the demo page: http://powerkiki.github.com/ie_expand_select_width/

disclaimer: I coded that thing, patches welcome :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment