Rahul Desai
Rahul Desai

Reputation: 15491

contentEditable set caret inside a particular element

I am unable to set caret into the first <p> in the contentEditable <div>.

I have seen this solution but its for before or after the element. How do I get it into an element?

Here is what I have so far:

$('#content').on('click', function(){

  if($('#placeholder').length > 0)
    $('#placeholder').removeAttr('id').text('').focus();

});
#content{
    border: 1px solid black;
    min-height: 100px;
    padding: 20px;
}

#placeholder{
    color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id='content' contentEditable=true>
  <p id='placeholder'>placeholder</p>
</div>

It clears the placeholder and doesnt set the caret at all.

How do I fix this?

Upvotes: 0

Views: 95

Answers (2)

Oleg Berman
Oleg Berman

Reputation: 694

Before you read any further please address to Range (MDN) and getSelection (MDN).

This is a working fiddle.

Code inside the fiddle is very self-explainatory, but what I found interesting was: let's say we have

<p id='paragraph'>I want to focus on this text</p>

then we do (as expected):

var p = $('#paragraph');
range.selectNode(p[0]);

This is actually going to put caret (roughly speaking) before <p>, but we need to get inside <p>.

Surprisingly...

var p = $('#paragraph');
var textInsideP = p.childNodes[0]; // the text inside p counts as a ChildNode
range.selectNode(textInsideP);

Boom.

Upvotes: 0

Julien Gr&#233;goire
Julien Gr&#233;goire

Reputation: 17114

The problem you have is that you p element has no content and so has 0px height. Watching the console you can see that contenteditable often add a <br> when clicking on it, you can do the same here and you'll have your caret.

$('#content').on('click', function(){

  if($('#placeholder').length > 0)
    $('#placeholder').removeAttr('id').html('<br>').focus();

});
#content{
    border: 1px solid black;
    min-height: 100px;
    padding: 20px;
}

#placeholder{
    color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id='content' contentEditable=true>
  <p id='placeholder'>placeholder</p>
</div>

Upvotes: 1

Related Questions