I am attempting to add text at the precise location of the cursor within a contenteditable div by clicking on another element. This functionality works flawlessly when clicking on a button, however, it does not work with any other element. Specifically, when I click on a button, the text is inserted at the cursor position, whereas for any other element clicks, it always adds the text at the beginning of the div. The code below demonstrates this behavior with both a Button click and a DIV click (note that it does not work for any other tag). What could be causing this discrepancy between the two types of clicks? Is there a way to make a DIV click behave exactly like a button click? Please keep in mind that JQUERY is not being used (though a solution involving VUEJS would also be acceptable). Thank you.
Here is the jsfiddle link http://jsfiddle.net/jwvha/2727/
function insertTextAtCursor(text) {
document.getElementById('pre').focus();
var sel, range, html;
sel = window.getSelection();
range = sel.getRangeAt(0);
range.deleteContents();
var textNode = document.createTextNode(text);
range.insertNode(textNode);
range.setStartAfter(textNode);
sel.removeAllRanges();
sel.addRange(range);
}
body {
background-color: #CCC;
}
div {
border: 1px #000 solid;
background-color: #FFF;
width: 900px;
margin-left: auto;
margin-right: auto;
text-align: center;
margin-top: 20px;
margin-bottom: 20px;
vertical-align: center;
padding: 30px;
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Editor</title>
</head>
<body>
<div contenteditable id="pre">
Update text Here . This is contenteditable div
</div>
<div>
<input type="button" onClick="insertTextAtCursor('TEXT')" value="Click here to insert text above"> ( This button inserts text at the cursors current positions)
</div>
<div onClick="insertTextAtCursor('TEXT')">
<b>Click here to insert in the above contenteditable div </b> ( This won't insert at the current position , but always at the position 1)
</div>
</body>
</html>