JSFiddle - React, Tailwind, and code Playground
HTML
<input type="button" id="strong" value="strong" />
<div class="text-div" contenteditable="true">
this is some text.<br>
this is <strong>strong</strong> text.<br>
firs select some text then click button,<br>
then click here to unselect and click button and type a character.
</div>
CSS
.text-div{
height:300px;
border:solid 1px #666666;
padding:2%;
font-size:18px;
}
JavaScript
var
HtmL="",selection;
$(document).ready(function(){
var
div = $('.text-div')[0];
$(document).on('keyup mouseup',div,function() {
getSelectionHtml();
selection = saveSelection(div);
});
$('#strong').click(function(){
if(HtmL!="")//if text selected
{
restoreSelection(div,selection);
replaceSelectionWithHtml('<strong>'+HtmL+'</strong>');
}else //if text not selected
replace();
});
function replace() {
var key = true;
restoreSelection(div, selection); //restore the pointer position in div
$(div).focus().keydown(function (evt) {
if (key) //prevent from repeat
{
evt.preventDefault();
evt = evt || window.event;
var charCode = typeof evt.which == "number" ? evt.which : evt.keyCode;
var keyChar = String.fromCharCode(charCode); //this Does'nt work well
replaceSelectionWithHtml('<strong>' + keyChar + '</strong>');
key = false;
}
});
}
});
function getSelectionHtml() {
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
HtmL = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
HtmL = document.selection.createRange().htmlText;
}
}
return HtmL;
}
function replaceSelectionWithHtml(html) {
var range, html;
if (window.getSelection && window.getSelection().getRangeAt) {
range = window.getSelection().getRangeAt(0);
range.deleteContents();
var div = document.createElement("div");
div.innerHTML = html;
...