R+D: Figure out how to make an auto-suggest field with Javascript Part 1

I've been trying to figure out how to make an auto-suggest widget in JavaScript. Generally, the hard part isn't setting up the AJAX transaction. (In my case its basically just a JSON transaction). The hard part is getting the silly suggestions to line up with your input field.

Well, today, you're in luck. I've figured out, (with the help of a few search engines, forums, and blog posts), how the heck to do this.

The tricky part is figuring out exactly where your input field is. (At least it was for me.) There are four words I'm going to list here - take note - they're very important:

  • offsetTop
  • offsetLeft
  • offsetWidth
  • offsetHeight

These are properties of an object in JavaScript that describe the object's position within it's parent object. (Obviously the height and width properties are fixed).

As a solution to the problem, you basically have to add up the offsetLeft and offsetTop values of the object, and all of it's parent objects in order to get its actual x/y coordinates in the browser. With this information, you can place a span, div or table with absolute positioning in that location with your suggestions in it.

The next hard part is writing a key handler that captures key presses and highlights/selects appropriate objects in your suggest box.

Comments