mauriciopastrana mauriciopastrana - 15 days ago 5
Javascript Question

Javascript keyboard events primer? (or rather: help me with my custom dropdown)

I need help finishing my custom built ajax [div] based dynamic dropdown.

Basically, I have an [input] box which;

onkeyup
, runs an Ajax search which returns a bunch of results in
div
s and are drawn back in using
innerHTML
. These
div
s all have highlights
onmouseove
r so, a typical successful search yields the following structure (pardon the semicode):

[input]
[div id=results] //this gets overwritten contantly by my AJAX function
[div id=result1 onmouseover=highlight onclick=input.value=result1]
[div id=result2 onmouseover=highlight onclick=input.value=result2]
[div id=result2 onmouseover=highlight onclick=input.value=result2]
[/div]


It works.. beautifully! looks elegant and is way more complete than any regular dropdown (those results div bring in a lot of information).

However, I'm missing the most of important functions behind regular HTML elements, that is, I can't keyboard down or up between "options". How do I do this? I know javascript handles keyboard events but; I haven't been able to find a good guide on how to do this. (Of course, the follow up question to this will eventually end up being: can I use
<ENTER>
to trigger that
onclick
event?)

Answer

What you need to do is attach event listeners to the div with id="results". You can do this by adding onkeyup, onkeydown, etc. attributes to the div when you create it or you can attach these using JavaScript.

My recommendation would be that you use an AJAX library like YUI, jQuery, Prototype, etc. for two reasons:

  1. It sounds like you are trying to create an Auto Complete control which is something most AJAX libaries should provide. If you can use an existing component you'll save yourself a lot of time.
  2. Even if you don't want to use the control provided by a library, all libraries provide event libraries that help to hide the differences between the event APIs provided by different browsers.

Forget addEvent, use Yahoo!’s Event Utility provides a good summary of what an event library should provide for you. I'm pretty sure that the event libraries provided by jQuery, Prototype, et. al. provide similar features.

If that article goes over your head have a look at this documentation first and then re-read the original article (I found the article made much more sense after I'd used the event library).

A couple of other things:

  • Using JavaScript gives you much more control than writing onkeyup etc. attributes into your HTML. Unless you want to do something really simple I would use JavaScript.
  • If you write your own code to handle keyboard events a good key code reference is really handy.