Making HTML5 datalist visible when focus event fires on input

html, javascript, jquery

Solution

I use the following code:

<input name="anrede" 
    list="anrede" value="Herr" 
    onmouseover="focus();old = value;" 
    onmousedown = "value = '';" 
    onmouseup="value = old;"/>

<datalist id="anrede">
    <option value="Herr" selected></option>
    <option value="Frau"></option>
    <option value="Fraulein"></option>
</datalist>

mouseover: Set focus and memorize old value in a -- g l o b a l -- variable

mousedown: Delete value and show `datalist` (built in functionality)

mouseup: Restore old value

Then select new value.

Find this an acceptable workaround towards a combobox.

Problem

As some might know already styling select element is a nightmare, literally impossible without some javascript trickery. The new datalist in HTML5 could serve the same purpose since the user is presented with a list of options and the value is recorded in an input text field. The limitation here is the list does not appear until the user start typing something in the text field and even then is only shown possible matches based on their input. The behavior I want is that as soon as there is focus on the field the entire list of options become visible. So I have this code - view on jsbin ``` <!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>Input - Datalist</title> </head> <body> <input list="categories"> <datalist id="categories"> <option value="Breakfast">Breakfast</option> <option value="Brunch">Brunch</option> <option value="Lunch">Lunch</option> <option value="Dinner">Dinner</option> <option value="Desserts">Desserts</option> </datalist> </body> </html> ``` and I'm trying to get that to show with this Javascript: ``` var catVal = document.getElementsByTagName("input")[0], cat = document.getElementById("categories"); catVal.style.fontSize = "1.3em"; catVal.addEventListener("focus", function(event){ cat.style.display = "block"; }, false); ``` Any help would be appreciated, Cheers

Original source