Why does select with onfocus not work in IE?

10,179

After a little bit of testing, it appears to me that IE doesn't open the dropdown if the style is modified in any way.

Yeah, good bug catch there. Anything that changes the select box (including any style change, even one triggered by changing a parent className) makes IE recreate the OS widget for it, which has the side-effect of closing it. So the dropdown is opened, but immediately closed before rendering. If you put a timeout on the background change function you can see it happen afterwards.

What you would need would be an event first just before focusing, so you can change the style, causing the dropdown to close, before it opens. Luckily, there is one! But it's IE-only. For other browsers (including IE8), best stick to the simple CSS :focus selector:

<style>
    select { background-color: #BDE5F8; }
    select:focus, select.focus { background-color: white; }
</style>
<select>
        <option>choose...</option>
        <option>1</option>
        <option>2</option>
        <option>3</option>
</select>

<!--[if lt IE 8]><script>
    // Fix lack of :focus selector for select elements in IE7-
    //
    var selects= document.getElementsByTagName('select');
    for (var i= selects.length; i-- >0;) {
        var select= selects[i];
        select.onfocusin= function() {
            this.className= 'focus';
        };
        select.onfocusout= function() {
            this.className= '';
        };
    }

    // Or, the same expressed in jQuery, since you mentioned using it
    //
    $('select').bind('focusin', function() {
        $(this).addClass('focus');
    }).bind('focusout', function() {
        $(this).removeClass('focus');
    });
</script><![endif]-->
Share:
10,179
Tim Büthe
Author by

Tim Büthe

Updated on August 16, 2022

Comments

  • Tim Büthe
    Tim Büthe over 1 year

    I want to highlight a select element with a background color to indicate, it is mandatory. When the user opens the menu by clicking on it, I want to remove the background color, so it looks nicer and is more readable. This works just fine in Firefox, Chrome and even IE6, but on IE7 & 8 the pulldown doesn't open on the first click (or is opened and closed very fast), only on the second.

    <select 
        style="background-color: #BDE5F8"
        onfocus="this.style.backgroundColor='#fff'"
        onblur="this.style.backgroundColor='#BDE5F8'">
        <option>choose...</option>
        <option>1</option>
        <option>2</option>
        <option>3</option>
    </select>
    

    How can I fix this?