Placing the caret outside of a dynamically created span

So, I looked through the piles of information on SO on the subject and finally got to the question.

I'm working with a div contenteditable

and I need to emulate a twitter on the fly converting from jagged text to styled text for hashtags and mentions (please don't link me to twitter text, i.e. not in and of itself, answer, I've tried).

The obvious solution here would be to attach the text to be styled in between, or more generally to something I can attach styles to.

I can do this, but the problem is that the caret then does strange things like going to the beginning.

I found a solution ( Tim Down's ) that works nicely, but it leaves the caret in between, so the text that follows is still framed, which is not what I want.

He suggests elsewhere that this is because webkit browsers are stubborn and will force the caret in-between instead of placing it out of range. There are two suggested hacks, first, it assumes that you enclose the text in a

, not in, gaps. Which I tried but doesn't work. Then it suggests creating a zero-width empty space char and then selecting it.

So how do I go about doing this? Or are there other alternatives?

(working code is appreciated)

Edit 1:

The reference to "cursor" has been corrected to "caret"

+3


source to share


2 answers


Could you put the content in the label instead of the span?

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

Please see 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 "Say Something"

Hope it helps!

0


source


This may be a duplicate of this question . Dutzi in this question recommended adding tags display: inline-block

and <br>

.

If you've seen that, or that doesn't work, you can add null bytes as a character to the string with var string += '\0';

or var string += '\u00000';

and choose that the null bytes with



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

      

If that's not what you mean (I'm not 100% clear what exactly happens without the code), there might be other solutions, but for now, that's how to add and select zero character length in JavaScript.

0


source







All Articles