views:

448

answers:

2

I have read a few posts on positioning the caret, but none seem to answer my particular issue.

  1. I have 2 divs (div1 and div2)
  2. div1 = noneditable div
  3. div2 = contenteditable div
  4. both divs contain exact same contents
  5. when user clicks on div1, it gets hidden, and div2 appears in exact location and user can edit

The problem: I want the caret to appear in exact location on div2 as div1

So, I need some way to READ the location where the user clicks on div1, and then when div2 appears place the cursor/caret in that same location, so a getCaretLocation(in_div_id) and setCaretLocation(in_div_id) set of functions.

Any way to do that?

Thanks -

+3  A: 

Short answer : You can't

Long answer : The problem you'll face is that you'll be able to get (x,y) coordinates for the click event on div1, but any implementation of the caret position while require you knowing the position of the caret in the content (which is the number of characters preceding the caret).

To convert the (x,y) coordinates to a character position you actually need to know how many characters were before (ie. left on the current line and above, if the text is ltr).

If you use a fixed width font, you can simplify the problem : mapping an (x,y) coordinate to a (line, column) coordinate on a character grid.

However, you still face the problem of not knowing how the text is wrapped. For example :

------------------
|Lorem ipsum     |
|dolor sit amet  |
|consectetur     |
|adipiscing elit |
------------------

If the user clicks on the d in dolor, you know that the character is the 1st on the 2nd line, but without knowing the wrapping algorithm there is no way you'll know that it is the 13th character in "Lorem ipsum dolor sit…". And there is no guarantee that such a wrapping algorithm is identical across browsers and platform.

Now, what I'm wondering is why would you use 2 different synced div in the first place ? Wouldn't it be easier to use only one div and set its content to editable when the user clicks (or hovers) ?

Adrien Friggeri
using 2 divs because i am enabling user to DRAG div around, which interferes with SELECTING text (highlighting to make bold for example).
OneNerd
thinking maybe I can get coordinates and trigger click() event with same coordinates on div2 -- will try and see how it works.
OneNerd
@OneNerd: I'd lean toward a handle or something for the dragging, but without knowing what the rest of your UI is, I wouldn't know if that makes sense for what you're doing.
T.J. Crowder
yeah - triggering a click at coordinates not working. voting your answer up since it is thorough and helps. thanks -
OneNerd
A: 

It sounds like you are trying to do an inline edit... have you looked at the jeditable plugin?

fudgey