views:

855

answers:

3

I have a contentEditable div.

Let's say the user clicks a button that inserts HTML into the editable area.

So, they click a button and the following is added to the innerHTML of the contentEditable div:

<div id="outside"><div id="inside"></div></div>

How do I automatically place the cursor (ie caret) IN the "inside" div? Worse. How can this work in IE and FF?

+1  A: 

As far as i could understand from your question:

If it is contentEditable editable/typeable, you may try this:

  // you insert content with your code and after that
  document.getElementById('contentEditable_id_here').focus();
Sarfraz
Yes, that sets the focus on the main contentEditable div, but I'm looking to put the cursor (or caret) in the <div id="inside"></div> tags so when the user starts typing, that's where there cursor is already.
Ben Mc
+3  A: 

For IE:

var range= document.body.createTextRange();
range.moveToElementText(document.getElementById('inside'));

range.select();

For Mozilla:

var range= document.createRange();
range.selectNodeContents(document.getElementById('inside'));

var selection= window.getSelection();
selection.removeAllRanges();
selection.addRange(range);

In theory the Mozilla version should also work in Webkit and Opera. In practice Webkit selects nothing and Opera selects the whole page. Sigh. This is still not well-supported territory.

bobince
A: 

I want to have the opposite effect in FF. I mean if I insert <div id="outside"><div id="inside"></div></div> using the execCommand I want the cursor placed outside both the divs. FF seems to place it in the innermost div

macveera