How to set index of a multiple select object to be selected when mouse moves over that index’s option. for example in the next html code, when mouse move over option 1, it will be selected. I want to do it all in JavaScript without editing the html code.
<select size="6" multiple="multiple">
<option value="1">option 1</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
<option value="4">option 4</option>
<option value="5">option 5</option>
<option value="6">option 6</option>
</select>
What happens is that explorer does not fire any events for the options tag, nor does it allow us to get its coordinates or dimensions so i think that the only thing left to do is trick the browser a little:
children of the select object are options… i guess some are text
nodes because we use white space to indent the HTML, so i’m using the
second child (options[1]) in order to obtain a reference to the
first [option] element.
displayed and won’t effect the content.
font-size style (this is the trick, i’m trying to calculate the
height of the [option] element by its font-size. sometimes this
value is specified in points (e.g. 10pt) so i’m creating a div with
exactly the same value for its height and asking the browser to give
the height back to me in pixels. Once i have the height of the
[option] element, the rest is trivial.
of the mouse and divide by the height of the [option] element. This
will give us the element on which the mouse is currently positioned
(mouse top position – select top position converts from screen
coordinates to the select box coordinates and dividing by the height
of the [option] element gives us the current [option].
selectedIndex.
Code:
For the rest of the browsers the treatment is much simpler:
Don’t forget to give the [select] the proper id (id=”mySelect”) & add onmousemove=”select( event )” on the [select] as well.
This worked for me on: Chrome, FireFox (3.6), Explorer 8, Explorer 6 (emulated), Opera & Safari.
Remember to remove the test DIV from the document when we’re done with it, otherwise there will be a bunch of unused DIVs in the DOM, so at the end of ieElementFromPoint() add:
document.body.removeChild( d );
Hope this help.