3

When I clear the contents of a contenteditable div, the cursor is lost immidiately and I can't bring it back by clicking.So I can't add anything if I clear it once.

Here check it out:

<div contenteditable>
  asdasd
  <div contenteditable="false">x</div>
</div>

Delete the 'asdasd' from the first line. As soon as you delete the last deletable character, the cursor is gone and I can't bring it back.

I just tried it in firefox and it works fine. So this is specific to chrome.

Achshar
  • 5,153
  • 8
  • 40
  • 70
  • I don't have any problem with that. My issue is that as soon as the element becomes empty, the cursor disappears and I loose focus without clicking anything. If someone is typing something and wants to clear the area, they can't write anything after that. – Achshar Jul 21 '16 at 00:41
  • make an example: http://jsbin.com/ – greggreg Jul 21 '16 at 00:47

2 Answers2

1

This should solve your problem. You can click that area even after it is empty and get your cursor back. Checkout the following link:

Restore cursor position after changing contenteditable

Community
  • 1
  • 1
UIPassion
  • 120
  • 7
  • It already works like that if the content is empty. But my code has another non editable div in it. Which messes with it. – Achshar Jul 21 '16 at 01:32
  • See if you can avoid the nesting of the 2 contenteditables. I just tried to make the second div outside of the parent, it works then. Also, instead of making the whole parent div contenteditable, or you can add another div like:
    asdasd
    x
    – UIPassion Jul 21 '16 at 03:05
  • Yeah that was a solution but for me that complicates many other things that I skipped over here. This works as intended in firefox btw, so only chrome screws it up. – Achshar Jul 21 '16 at 03:56
1

.container {
  display: flex;
  flex-direction: column;
  outline: none; 
}
.edit-area {
  border-right: solid rgba(0,0,0,0) 1px; 
  outline: none; 
  min-height: 19px;
}
<div class="container" contenteditable>
  <div class="edit-area" contenteditable>
    Delete this text
  </div>
  <div contenteditable="false">x</div>
</div>

There is the potential to go down quite the rabbit hole on this one. I've seen solutions with 100's of lines of javascript.

I found the trick is to separate the x from the contenteditable.

I also add the alpha zero border right to force the block to render. In this case it works without it because of the flex box, but I've seen other cases where it just doesn't work without it - so I thought I'd share.

The min-height is also important to force it not to disappear when height goes to 0 if content is deleted.

I also wrapped the whole thing in a contenteditable to prove the point that it does work as a child of a contenteditable container.

Essentially this enables you to have an empty contenteditable and retain the flashing cursor.

Justin Vincent
  • 1,329
  • 2
  • 14
  • 22