Monday, November 5, 2012

how set the dropdown list item size based on lenght in I.E 6

The width of the dropdown grows/shrinks during a mouseover.

here is code to do that :-


<script type="text/javascript">
    var MAX_WIDTH = 500; //the biggest width the select is allowed to be

    function biggestOption(elem) {
     var biggest = 0;
     for (var i=0;i<elem.options.length;i++) {
      if ( elem.options[i].innerHTML.length > biggest ) {
       biggest = elem.options[i].innerHTML.length;
      }
     }
     return roughPixelSize(biggest);
    }

    function roughPixelSize(charLength) {
     //this is far from perfect charLength to pixel
     //but it works for proof of concept
     roughSize =  30 + (charLength * 6);
     if (roughSize > MAX_WIDTH) {
      return MAX_WIDTH;
     } else {
      return roughSize;
     }
    }

    function resizeToBiggest(elem) {
     elem.style.width = biggestOption(elem);
    }

    function resizeToSelected(elem) {
     elem.style.width = roughPixelSize(elem.options[elem.selectedIndex].innerHTML.length);
    }

</script>

<select onmouseover="resizeToBiggest(this)" style="width:70px" onchange="resizeToSelected(this)" onblur="resizeToSelected(this)" >
    <option>test 1</option>
    <option>test 2</option>
    <option>test 3</option>
    <option>this is some really really realy long text</option>
    <option>test 4</option>
    <option>test 5</option>
</select>

No comments:

Post a Comment