Search code examples
javascripthtmlpositionhtml-select

JavaScript get position of option element?


I have a web app that needs to know the position (x/y not index!) of an option element inside a multi select list. It works great in Firefox but no dice in Chrome or IE.

Is it possible to get an option's position in Chrome/IE with JavaScript?

Here is my fiddle displaying the issue: http://jsfiddle.net/jamiller619/Kbh4g/3/ Works with Firefox but not in IE/Chrome.


Solution

  • Short answer - you can't (webkit issue).

    But you can cheat!!!

    HTML:

    <div style="position:relative">
    <select multiple="multiple">
        <option>Test 1</option>
        <option>Test 2</option>
        <option>Test 3</option>
        <option>Test 4</option>
        <option>Test 5</option>
        <option>Test 6</option>
        <option>Test 7</option>
        <option>Test 8</option>
        <option>Test 9</option>
        <option>Test 10</option>
    </select>
    </div>
    <br />
    option position:<br />
    Left: <span id="pos-x"></span><br />
    Top: <span id="pos-y"></span>
    

    CSS:

    select
    {
        font-size:20px;    
    }​
    

    JQuery:

    $(function()
    {    
        $('select').change(function() {
            var optionHeight = 20; // or get this value from the stylesheet or inline-style
            var textIndent = 1; // best guess or work it out using coordinate crosshair tool
            $('#pos-y').text((this.selectedIndex + 1) * optionHeight);
            $('#pos-x').text(this.offsetLeft + textIndent);
        });
    });
    

    It's a quick and dirty solution!

    UPDATE

    CSS:

    select
    {
        height: 150px;
        font-size: 20px;        
    }
    

    ​ JQuery:

    $(function()
    {    
        $('select').change(function() {
            var fontSize = 20; // or get this value from the stylesheet or inline-style
            var lineHeight = fontSize + 4 // need a better calculation here
            var optionHeight = lineHeight;
            var textIndent = 1; // best guess or work it out using coordinate crosshair tool
            var top = (this.selectedIndex * optionHeight) - this.scrollTop; 
            $('#pos-y').text(top);
            $('#pos-x').text(this.offsetLeft + textIndent);
        });
    });