JSFiddle - React, Tailwind, and code Playground
by lustre
HTML
<div id="editable" class="editable" contenteditable="true">Edit</div>
CSS
.highlight {color:red;}
.editable {border: 1px solid #aaa;}
JavaScript
$('#editable').keyup(function(e){
$this = $(this);
if(e.keyCode == 32){
return false;
}
if ($this.html().length > 10){
var content = $this.html();
var trimmed = $this.html().substring(0,10);
var extra = content.match(/.{10}(.*)/)[1];
// check if highlight span already exists first
if($('.highlight').length){
$('.highlight').html(extra);
var styledExtra = $('.highlight').html();
} else {
var styledExtra = "<span class='highlight'>"+extra+"</span>";
}
var range = document.createRange();
var startNode = document.getElementById("editable");
console.log(trimmed);
console.log(styledExtra);
$this.html(trimmed + styledExtra);
setEndOfContenteditable(startNode);
}
});
function setEndOfContenteditable(contentEditableElement){
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.selectNodeContents(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
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
}
}