views:

114

answers:

2

I got multiple <p contenteditable="true"></p> elements on a page. I'm looking for a solution to use arrow keys for navigating across those disjoint elements just as if they were one single editable element.

So for instance, if the caret is at the 10th character on the last line of the 1st paragraph and the user hits the down arrow key, the caret should jump to the 2nd paragraph and place the caret at the 10th character (if there's one) on its first line.

Appreciate any comments.

+1  A: 

What if you would make the container element editable, instead of every single paragraph? For example:

<div contenteditable="true">
    <p>Lorem ipsum</p>
    <p>dolor sit</p>
</div>
bogdanvursu
makes total sense, but that would make the paragraphs deletable among other unsolicited side effects of a contenteditable container div. I need to stick with many paragraphs instead.
Alex
@Alex, instead of trying to maintain indefinite paragraphs, perhaps you should maintain a parent and replace the child paragraphs with empty ones if they are deleted.
eyelidlessness
A: 

Revised answer

You can detect that the caret is at the start or end of the current editable element by using something like the following (example is for down array on the last line):

  • Detect the down arrow keydown event
  • Check if the caret is at the end of the paragraph by doing one of the following:
  • Create a Range (or TextRange in IE) from the selection object and comparing it to another Range that encompasses the whole paragraph. This is the slightly trickier but more seamless option. OR:
  • Store the selection and set a brief timer (say 1 millisecond) to allow the keypress to take effect. The function passed to the timer calls compares the current selection with the previously stored selection. If they're the same, the caret has not moved and must have been at the end of the paragraph.
  • If the caret is at the end of the paragraoph, move it to the start of the next editable paragraph.

This isn't the the usual behaviour of the caret but is reasonably easy to achieve and could be a reasonable compromise. The problem is that there's no reliable cross-browser way to work out the caret's coordinates.

Tim Down
in fact, when you're pressing the down arrow key on the last line, the caret won't remain on the same position but jump to the very end of the paragraph. So you're solution could potentially work if one could determine wether the caret is at the end position of the editable element. Any idea on that?
Alex
Ah, good point. You then have a problem if the caret is in the line above the final line and directly above the final character: the caret would go to the end of the paragraph, which would be indistinguishable from the case when the caret has been on the last line. To be honest, I'm not sure this workable.
Tim Down
I've updated my answer.
Tim Down