views:

345

answers:

2

I currently maintain an add-on for Firefox that adds a number of capabilities to a forum web site that implements its own markup language, similar to what stackoverflow provides with "Markdown."

I have built an IntelliSense function for this add-on, which, similar to Visual Studio, will pop up an auto-suggest when typing this markup in a textarea. Example:

The hardest thing about the implementation is finding the (x,y) coordinates of a key press in a textarea so I can pop-up the IntelliSense window very close to it. The keypress events in JavaScript do not expose these coordinates, so I've had to work around this. Unfortunately I could only find a cross-browser compatible way of getting the y-coordinate, not the x-coordinate. The code for this is located here in the _getPopupPoint function.

This works for Firefox because I use some of Mozilla's XPCOM interfaces to get the coordinate. So while this works for Firefox, now that I want to port my add-on to Google Chrome, I couldn't find a way to get the coordinates.

So what I'm asking is twofold: (1) Is there a better way to get the x-coordinate of a key press? (2) If not, is there anything I can do in the context of a Google Chrome add-on to get the same data?

A: 

It coculd be interesting to checkout the implementation of event object in DOJO toolkit.

Dojo provides the following attributes with an event object:

  • event.target - the element that generated the event
  • event.currentTarget - the current target
  • event.layerX - the x coordinate, relative to the event.currentTarget
  • event.layerY - the y coordinate, relative to the event.currentTarget
  • event.pageX - the x coordinate, relative to the view port
  • event.pageY - the y coordinate, relative to the view port
  • event.relatedTarget - For onmouseover and onmouseout, the object that the mouse pointer is moving to or out of
  • event.charCode - For keypress events, the character code of the key pressed
  • event.keyCode - for keypress events, handles special keys like ENTER and spacebar.
  • event.charOrCode - a normalized version of charCode and keyCode, which can be used for direct comparison for alpha keys and special keys together. (added in 1.1)
Shailesh Kumar
The normal KeyboardEvent passed to a keypress event listener will have most of these properties, too, but the layerX/layerY and pageX/pageY properties are 0. I just tried with Dojo, and the properties also remain at 0.
David DeWinter
+1  A: 

The window.getSelection and related methods might be what you're looking for. You can calculate the screen position of the caret using the offset etc functions.

jonchang
This looks close to what I want. However, the anchorOffset and focusOffset properties reset to 0 at the beginning of every line feed character. This means if the user types a paragraph I can't accurately find the x-coordinate because the paragraph spans multiple lines in the text area.
David DeWinter