1

I have a simple snippet of code that injects an element into a contenteditable and places the user's cursor inside it. It works well in every modern browser except Firefox. Any ideas on why this isn't working (any help appreciated)?

Live demo at CodePen: http://codepen.io/ashblue/pen/slwJu

function forceInjectAndFocus () {
  var range = document.createRange();
  var sel = window.getSelection();
  var child = $('#editor').html('<p class="test">a</p>').children().first().get(0);

  range.setStart(child.firstChild, 0);
  sel.removeAllRanges();
  sel.addRange(range);
  $(child.firstChild).detach();
}
Ash Blue
  • 5,344
  • 5
  • 30
  • 36

1 Answers1

0

Why are you removing the text node? You're leaving things in the lap of the gods if you remove the node containing the selection. I'd suggest just placing the caret inside an empty <p> element:

function forceInjectAndFocus () {
  var range = document.createRange();
  var sel = window.getSelection();
  var p = document.createElement("p");
  p.className = "test";
  document.getElementById("editor").appendChild(p);
  range.setStart(p, 0);
  range.collapse(true);
  sel.removeAllRanges();
  sel.addRange(range);
}

Demo: http://codepen.io/anon/pen/BIHsG

Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Adding or removing the text inside doesn't seem to make a difference from my tests. It actually makes Chrome play nicer oddly. On the other hand it looks like your example is broken. Text is showing up outside the

    tag when you type.

    – Ash Blue Apr 28 '14 at 19:27
  • @AshBlue: True. The problem with your example in Chrome (on my Windows machine, at least) is that the caret doesn't appear until you start typing. I haven't yet found a way to make the caret appear and be positioned inside the `

    `.

    – Tim Down Apr 28 '14 at 22:46
  • Yeah no way around the caret (some sort of bug). I've been finding that contenteditable is hellabuggy in certain situations. – Ash Blue Apr 28 '14 at 23:36