Open Select using Javascript/jQuery?

Newbie picture Newbie · Jan 12, 2010 · Viewed 82.2k times · Source

Is there a way to open a select box using Javascript (and jQuery)?

<select style="width:150px;">
    <option value="1">1</option>
    <option value="2">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc arcu nunc, rhoncus ac dignissim at, rhoncus ac tellus.</option>
    <option value="3">3</option>
</select>

I have to open my select, cause of IE bug. All versions of IE (6,7,8) cut my options. As far as I know, there is no CSS bugfix for this. At the moment I try to do the following:

var original_width = 0;
var selected_val = false;

if (jQuery.browser.msie) {
    $('select').click(function(){
        if (selected_val == false){
            if(original_width == 0)
                original_width = $(this).width();

            $(this).css({
                'position' : 'absolute',
                'width' : 'auto'
            });
        }else{
            $(this).css({
                'position' : 'relative',
                'width' : original_width
            });
            selected_val = false;
        }
    });

    $('select').blur(function(){
        $(this).css({
            'position' : 'relative',
            'width' : original_width
        });
    });

    $('select').blur(function(){
        $(this).css({
            'position' : 'relative',
            'width' : original_width
        });
    });
            
    $('select').change(function(){
        $(this).css({
            'position' : 'relative',
            'width' : original_width
        });
    });

    $('select option').click(function(){
        $(this).css({
            'position' : 'relative',
            'width' : original_width
        });
    
        selected_val = true;
    });

}

But clicking on my select the first time will change the width of the select but I have to click again to open it.

Answer

jake the snake picture jake the snake · Jan 13, 2010

Instead of using click, you could use the mousedown handler to capture the mousedown event. mousedown fires before click, so you could call stopPropogation to break the event queue.