JSFiddle - React, Tailwind, and code Playground
HTML
<p contenteditable = "true" >Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse dui turpis, pretium non cursus ut, venenatis ac arcu. Integer interdum velit et arcu aliquam euismod. Phasellus a mi ac nulla sagittis fringilla. Vivamus vitae odio lectus. Nulla mattis venenatis volutpat. Etiam magna tellus, ullamcorper vel tristique eu, molestie at mauris. Nulla pharetra odio vel ante eleifend volutpat adipiscing mauris ullamcorper. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Proin consequat hendrerit posuere. Curabitur adipiscing semper elit, ut tempus tortor varius a.</p>
<p contenteditable = "true" >Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse dui turpis, pretium non cursus ut, venenatis ac arcu. Integer interdum velit et arcu aliquam euismod. Phasellus a mi ac nulla sagittis fringilla. Vivamus vitae odio lectus. Nulla mattis venenatis volutpat. Etiam magna tellus, ullamcorper vel tristique eu, molestie at mauris. Nulla pharetra odio vel ante eleifend volutpat adipiscing mauris ullamcorper. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Proin consequat hendrerit posuere. Curabitur adipiscing semper elit, ut tempus tortor varius a.</p>
CSS
p {border: solid 1px red}
JavaScript
function setCaret(contentEditableElement, index)
{
var range,selection;
if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
{
range = document.createRange();//Create a range (a range is a like the selection but invisible)
range.setStart(contentEditableElement,index);
range.collapse(true);
selection = window.getSelection();//get the selection object (allows you to change selection)
selection.removeAllRanges();//remove any selections already made
selection.addRange(range);//make the range you have just created the visible selection
}
else if(document.selection)//IE 8 and lower
{
range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
range.select();//Select the range (make it the visible selection
}
}
$(document).on('keydown', 'p[contenteditable="true"]', function(e) {
if(e.which == 13) {
e.preventDefault();
setCaret($(this).get(0), 5);
};
});