3

So I have perused the piles of information on SO on this subject and finally resorted to asking.

I'm working with a contenteditable div and need to mimic twitter's on-the-fly conversion from unstyled text to styled text for hashtags and mentions (please do not link me to twitter-text, that is not, in and of itself, the answer, I've tried).

The obvious solution here would be to enclose the text that needs to be styled in a span or, more generally, something I may attach styles to.

I can do that, but the problem is that the caret then does weird stuff like jump to the beginning.

I've found a solution (Tim Down's) which works nicely, but it leaves the caret in the span, so the ensuing text is still styled, which is not what I want.

He suggests elsewhere that this is because webkit browsers are opinionated and will force the caret in the span, instead of placing it outside of the span. There are two proposed hacks, first, he suggests that you enclose the text in a blocks instead of spans. Which I've tried, but doesn't work. He then suggests that I create a zero width white-space char, and then select that.

So how do I do that? Or are there any other alternatives?

(working code welcome)

Edit 1:

Reference to "cursor" was corrected to "caret"

Community
  • 1
  • 1
nmac
  • 610
  • 1
  • 10
  • 20

2 Answers2

0

Can you please try placing the content in the label instead of span ?

That will force the caret position to be at the end.

Please check with the following code....

<!DOCTYPE html>
<html>
<head>
    <title>Demo</title>
    <script language="javascript">
        function addSomeText()
        {
            var dynaspan = "<label>"+new Date().getTime()+"</label>"
            document.getElementById("clickable").innerHTML += dynaspan;
        }   
    </script>
</head>
<body>
    <div style="width:auto;height:240px;border:1px solid red;" contenteditable="true" id="clickable">
    </div>

    <button onclick="javascript:addSomeText();">Say Something!</button></body>
</html>

Click on Say Something

Hope it helps!

Hemant
  • 1,999
  • 2
  • 12
  • 8
0

This may be a duplicate of this question. Dutzi, in that question, recommended adding display: inline-block and a <br> tag.

If you've seen that, or that doesn't work, you can add a null-byte-like character to a string with var string += '\0'; or var string += '\u00000'; and select that null byte with

input.setSelectionRange(input.value.length-1, 1);
input.focus();

If this is not what you mean (I wasn't 100% clear on what exactly was happening without code), there may be other solutions, but at the moment, that's how to add and select a zero-length character in javascript.

Community
  • 1
  • 1
Adviov
  • 480
  • 5
  • 17