Search code examples
javascripthtmlcontenteditablecaret

How to focus on <p> in contenteditable div


I'm using contenteditable div to make rich editor. My problem now is I can't get caret to be positioned on <p> right after I embed Instagram frame. What I tried is create new <p> and focus on it after I embed Instagram frame. But it doesn't work.

Does anyone know solution of this problem?

I make JSFiddle as example (I put one of embed code in CSS block)


Solution

  • Although the contenteditable spec states that it should be possible to place the cursor inside an empty p tag like this:

    <div>aaa<p>|</p>bbb</div>
    

    Webkit (Safari) and Blink (Chrome) currently do not support it. More info here.

    Fortunately, there is a relatively easy workaround. We just need to get some content inside the p tag, allowing us to place the cursor here. One option could be to append a textnode that contains a Zero Width Space. This approach is sometimes useful for situations involving inline tags.

    In your case, the most effective solution would be to simply append a line break to the paragraph. Contenteditable implementations typically treat line breaks inside block tags as a "temporary holding nodes", and the default handling is the same across major browsers. The initial result should look like this:

    <div>aaa<p>|<br></p>bbb</div>
    

    And as soon as you start typing, the BR will be replaced (the browser does this automatically):

    <div>aaa<p>inner text|</p>bbb</div>
    

    Even when you delete the inner text, the browser should automatically re-insert a line break, so you will always be able to get the cursor back inside.

    I've forked and updated your jsfiddle with an example here.