I have a contenteditable
div, something like:
<div id="text" contenteditable="true"></div>
What I would like is to place another div (or span, non-editable) at the start of #text
, where the user cannot insert text before it, or even move the cursor before it.
I've tried variations of:
<div id="text" contenteditable="true">
<span class="lead" contenteditable="false">This is some leader</span>
</div>
You can see a running version of this setup here.
One thing you'll notice is that I've inserted a blank character ​
after the </span>
. Without it, the cursor (carrot) does not display properly - either in the wrong spot, or not at all.
I'm not sure why, but in the fiddle I've provided, you cannot delete (backspace) the span
content. When I have this identical html running in my browser, from an HTML file, I can delete it. I would like the user to be able to delete it, if desired, but to not allow anything to be inserted in front of it. It should delete all at once - it's either there as a group (including the ​
), or not at all. Hence the contenteditable="false"
.
EDIT 1
It seems the non-deleting issue is purely the way the HTML is written. I've created a new post here commenting on it. That problem is solved, but the larger issue here is still ripe for the taking!
/EDIT 1
The closest I've gotten, using JS, is something like:
$('#testing').on('keyup', function(e){
if($(this).html().indexOf(... leader ...) == 3){ // Needs to be 3, because the actual content of an editable div has markup in it
}else{
var splits = $(this).html().split(... leader ...);
$(this).html(... leader ...);
for(var i = 0; i < splits.length; i++){
$(this).append(splits[i]);
}
}
});
which you can see running here.
What it does is checks to see if the desired bit is at the front. If not, it splits the content, and rearranges it so that the desired bit is back at the lead.
It's super buggy, has a lag after keyup, and prints the character before moving it around. It also doesn't work for the desired <span>
element previously discussed, and also keeps the cursor at the start of the input field if it began there.
Sorry if I've presented it confusingly. I'm trying to think of a service that offers the same functionality, but can't think of any off the top of my head. FaceBook has something similar, when you type a friend's name into a comment box, but the content is editable and can be anywhere in the input. Shown below:
Thoughts? Anything to get me in the right direction is welcome!