Fix for “IE Select DropDown with Fixed width issue” using jQuery
Problem
For Example, if the width of DropDown is 150px and option text is quite large and it doesn't fit in 150px, so IE will cut the option text where it works like charm in Firefox and Chrome. See below images.
Ahhh!! If you are viewing this post in IE then take a look at below Demo and otherwise copy the link "http://jsfiddle.net/jquerybyexample/cV9xv/embedded/result/" and open it in IE to see yourself.
Solution
So what is the solution? You can solve this problem either with JavaScript or with jQuery. The basic idea of solution is same, it just the implementation which differs in both the languages.
- First wrap the select dropdown in a div with width same as dropdown and "overflow:hidden" style.
//Code Starts <div style="width:150px;overflow:hidden;"> <select style="width:150px;"> </select> </div> //Code Ends
- Now when dropdown is clicked using mouse then set the width of dropdown to 'auto' so that it expands and reset it to fixed width when focus is out or item is selected. The reason for wrapping it in div is when it is set to 'auto', the dropdown extra width is hidden.
- So to implement this solution, we will be using "onmousedown","onchange" and "onblur" event.
JavaScript Solution
So first define two JavaScript functions. One which sets width to 'auto' and other reset it to original width.
//Code Starts <script type='text/javascript'> function SetWidthToAuto(drpLst) { drpLst.style.width = 'auto'; } function ResetWidth(drpLst) { drpLst.style.width = '150px'; } </script> //Code Ends
Now call these functions on various events with select dropdown.
//Code Starts <select id="drpTechnology" style='width:150px' onchange='ResetWidth(this)' onblur='ResetWidth(this)' onmousedown='SetWidthToAuto(this)'> //Code Ends
See Result below:
Well, the problem with above solution is that it is applicable in all browsers, but the issue is specific to IE. So let's modify the JavaScript code to execute only in case of IE.
//Code Starts var isIE = navigator.userAgent.toLowerCase().indexOf("msie"); function SetWidthToAuto(drpLst) { if (isIE > -1) { drpLst.style.width = 'auto'; } } function ResetWidth(drpLst) { if (isIE > -1) { drpLst.style.width = '150px'; } } //Code Ends
See Result below:
jQuery Solution
Below is jQuery code, which does the same as JavaScript code. Keep in mind, now you don't need to define these event which declaring select dropdown as with power of jQuery, we have attached it directly with the select dropdown.
//Code Starts $(document).ready(function() { $("#drpTechnology").mousedown(function() { if ($.browser.msie) { $(this).css("width", "auto"); } }); $("#drpTechnology").change(function() { if ($.browser.msie) { $(this).width(150); } }); $("#drpTechnology").blur(function() { if ($.browser.msie) { $(this).width(150); } }); });? //Code Ends
See Result below:
Feel free to contact me for any help related to jQuery, I will gladly help you.