2

Sample of what I mean:

http://jsfiddle.net/vXnCM/3717/

<div id="editable" contenteditable="true">
    text text text text <span id="test" style="color:red"></span>text text
</div>
<button id="button" onclick="setCaret()">focus</button>
<script language="javascript">
function setCaret() {
    var el = document.getElementById("test");
    var range = document.createRange();
    var sel = window.getSelection();
    range.selectNodeContents(el);
    range.collapse(false);
    sel.removeAllRanges();
    sel.addRange(range);
    el.focus();
}
</script>

Open the link in Chrome and click Focus, then start typing. Your new text is red.

But if you delete the "ASDF" from the HTML and run it again, your new text is black.

How can I have it be red with no starting text in the div?

(Or, equally effective, how can I have it be red and then clear the starting text from the div without losing the cursor location?)

JBlitzen
  • 145
  • 11

2 Answers2

2

This is a common problem. Here is some background and potential solutions (none of them are ideal):

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • You're right, good call. Someone mentioned zero space characters to me after I posted the question and I came back to one of those links myself. I'm not in love with the zero space character solution since it complicates backspace and arrow key movement, but on the other hand it's a little clearer to the user that there's *something* special about that cursor location. So I went that route, and it'll work. Thanks! – JBlitzen Jan 27 '15 at 21:04
  • I'm still surprised, though, that the above code didn't work in Chrome. – JBlitzen Jan 27 '15 at 21:04
1

I'm not sure if this is what you want, but I think so, basically it's your range selection logic that needs to be revised. I don't delete the text, but highlight it so when the user types the text is removed, which I think might be what you want (a la 'start typing here').

function setCaret() {
    var el = document.getElementById("test");
    var range = document.createRange();
    var sel = window.getSelection();
    range.setStartBefore(el);
    range.setEndAfter(el);
    sel.addRange(range);
    el.focus();
}

Checkout the forked version here: http://jsfiddle.net/uhe76wup/

Good reference to learn about Range: https://developer.mozilla.org/en-US/docs/Web/API/Range

joseeight
  • 904
  • 7
  • 10
  • Not a bad concept but it's not really workable, since the goal is to have a way to appy a new format to any new text written at the cursor location. – JBlitzen Jan 27 '15 at 21:02