3

I have contenteditable div with non-editable "islands". Everything is working well until non-editable part is the last thing in editable div. In that case cursor is not right behind non-editable but at the very end of editable div.

See this example I borrowed from this question

Here is fiddle you can try on: http://jsfiddle.net/RYsvZ/2/ . When you delete dot at the end, cursor jump away. This behaviour is with safari and chrome. I guess it is webkit issue.

Here is code sample:

<div contenteditable="true" class="editor">
Sample template with <span class="mergecode" contenteditable="false">MergeCode1</span>.
</div>

Do you have any idea why it is happening and how to fix it?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
jendan
  • 271
  • 4
  • 14

2 Answers2

12
&zwnj;<button contenteditable=false>press</button>&zwnj;

The problem is caused by the caret having no space to go into so if you wrap your contenteditable divs in zero width non joining spaces it gives the caret somewhere to go.

jsfiddle

  • 1
    I'm still working on that, actually right know. I manage to come up with some workaround but it is a lot buggy. My solution: everytime when user change text, I look for last element of contenteditable and if it is noneditable part I put "ending" at the end. "ending" is empty span . There are lots of corner cases like: when you are editing you don't know if you edit before, after or insides of "ending" while it is empty tag. Also webkit creates empty text nodes if noneditable part is the last, so you have to deal with those too. – jendan Feb 12 '14 at 09:39
  • This is brilliant! Thank you!! – nachocab Apr 23 '17 at 00:14
  • wow this helped me so much. my issue was the cursor jumping to the left side and actually having a double cursor but this solved it – MilesStanfield Apr 23 '17 at 05:24
3

This happens when contenteditable=false is last child of

element. As I know, this is webkit bug. You always make sure the "contenteditable=false" is wrapped a hidden_char or zero-width-white-space:

  • HIDDEN_CHAR: "\ufeff"
  • ZERO_WIDTH_WHITESPACE: "​"

If you use tinymce, you can use onNodeChange event or check when delete/backspace happens and validate all "contenteditable=false" nearby the cursor.

Tung Dang
  • 31
  • 1