1

How to make contenteditable cursor appear on focus when the contenteditable element is empty? See code below and JSFiddle to demo.

HTML

<p>type here:
    <span id="contentEditable-name"></span>
</p>

JS:

var contenteditable_el = document.getElementById('contentEditable-name');
  contenteditable_el.contentEditable='true';
tim peterson
  • 23,653
  • 59
  • 177
  • 299

2 Answers2

3

Your JavaScript is fine, your problem is that the <span> is collapsing to 0 width and 0 height, because there's nothing inside of it. Thus, it cannot be clicked, and only receives focus when tabbed onto, etc. You can change the display property to inline-block or block and set a width on the element to solve this problem.

var contenteditable_el = document.getElementById('contentEditable-name');
contenteditable_el.contentEditable='true';

// Try commenting these two lines out
contenteditable_el.style.display = "inline-block";
contenteditable_el.style.minWidth = "20px";

contenteditable_el.style.outline = "1px solid red";
<p>type here:
<span id="contentEditable-name">

</span>
</p>
Hatchet
  • 5,320
  • 1
  • 30
  • 42
-1

I found that the HTML contents generated by the contenteditable code inside the div can have zero width and this causes the cursor to hide. Adding CSS such as this fixed it for me:

.contenteditablecontrol * {
    min-width: 5px;        /* arbitrary value to stop the cursor disappearing at the end of the editable text */
}
user2728841
  • 1,333
  • 17
  • 32