JSFiddle - React, Tailwind, and code Playground
HTML
<div contentEditable="true" class="parent">Some other editable content
<div class="field" contentEditable="false"> <span class="label">This is the label</span>
<span class="value" contentEditable="true">This is where the caret is</span>
</div>
<!-- cursor will be moved here on enter -->Here!
</div>
CSS
div { margin: 5px; padding: 2px; border: 1px solid blue; }
.label { font-weight: bold; }
JavaScript
$(function () {
$('.field .value').keydown(function (e) {
if (e.which == 13) {
e.preventDefault();
placeCaretAtEnd($(this).closest('.parent')[0]);
}
});
});
/**
This below function is copied from http://stackoverflow.com/a/4238971/297641
All credits goes to the original author.
*/
function placeCaretAtEnd(el) {
el.focus();
if (typeof window.getSelection != "undefined"
&& typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}