pelican_george
pelican_george

Reputation: 969

HTML5 contenteditable - nested non editable spans and cursor position behavior

I'm trying move the cursor around placeholders (tags) within a contenteditable div.

If you look at the following fiddle and screenshot:

contenteditable

using Chrome placing the cursor on the right side of the RED tag, if I push the left arrow key the cursor goes up right next to "some" instead of staying in the same line as the RED tag, on its left side.

Chrome seems to be the only browser where I'm experiencing this behavior. I could listen to key down events and somehow control this behavior, but that seems over the top and quite hacky.

Is there a reasonable explanation for this and a possible smooth workaround?

.red {
  background-color: red;
}
.orange {
  background-color: orange;
}
.id {
  color: white;
}
<pre>
<div dir="ltr" class="contenteditable" contenteditable="true">some<br><placeholder class="red" contenteditable="false" unselectable="on"><span class="id">ID</span> TAG</placeholder> <placeholder class="orange" contenteditable="false" unselectable="on"><span class="id">ID</span> TAG</placeholder> text
</div>
</pre>

<p>
Instructions:<br>
Put the cursor on the right hand side of the orange tag.<br>
If you move the cursor to the left you will notice 2 unwanted behaviors:<br>
1: the cursor is invisible inbetween the TAGs<br>
2: when the cursor is placed on the right side of the red tag, if you move to the left, it will go directly up right next to "some". The expected would be on the left side of the red tag.<br>
</p>

Upvotes: 0

Views: 499

Answers (1)

Martin Gottweis
Martin Gottweis

Reputation: 2739

This is tricky. The best I came up with is: https://jsfiddle.net/7u4o99o9/1/

.tag {
    display: inline-block;
    padding: 5px 5px;
}

.tag-body {
    padding: 3px;
    border-radius: 4px;
}

.red .tag-body {
    background-color: red;
}
.orange .tag-body {
    background-color: orange;
}

.id {
    color: white;
}

Another option is to use a ready-made library such as: http://xoxco.com/projects/code/tagsinput/example.html

Upvotes: 1

Related Questions