My Technical Notes

Wednesday, 6 February 2013

Expanding Select Elements in IE8 and lower

TODO rewrite

In IE8 and below, if you have a select element whose width is for example 300px, then if there are very long options, these cannot be seen properly. One can get around this limitation of IE by setting the width to 'auto' using jquery when the select is clicked. In the case of select elements embedded within td elements, we have to wrap the select in a div which we position relative, and set the select to position absolute. This way, the select will not shift around the cells of the table in which it is embedded.


$(function () {
    if ($.browser.msie && $.browser.version < 9) {
        $("select").each(function () {
            var outerWidth = $(this).outerWidth();
            $(this).css("width", "auto");
            var autoWidth = $(this).outerWidth();
            $(this).css("width", "");
            if (autoWidth > outerWidth) {
                if ($(this).parent()[0].tagName.toLowerCase() == 'td') {

                    var newDiv = $("<div />", {
                        "css": {
                            "height": $(this).parent().height(),
                            "width": "100%",
                            "position": "relative"
                        }
                    });

                    $(this).wrap(newDiv);

                    $(this).css('position', 'absolute');
                }

                $(this).bind('mousedown focus', function () {
                    $(this).css("width", "auto"); 
                }).bind("blur change", function () {
                    $(this).css("width", "");
                });
            }
        });
    }

    // make all browsers and whatever width show the selected option on hovering
    $('select').bind('hover mouseover', function () {
        $(this).attr('title', $(this).find('option:selected').text());
    });
});

No comments: