Method by which JS inserts content at the cursor position in an editable div

  • 2020-03-30 04:20:39
  • OfStack

This article is an example of how js can insert content in an editable div, just like the editor we use. The specific implementation method is as follows:

The first step is to have DIV enable edit mode

<div contenteditable=true id="divTest"></div>

Enable edit mode for div by setting contenteditable=true. This allows the div to type like a textbox.
Let's drop the subject. Here's how to get or set the cursor position.

2 steps:

Get the cursor position in DIV
Change the cursor position

var cursor = 0; //Cursor position & NBSP; < br / >
document.onselectionchange = function () {
var range = document.selection.createRange();
var srcele = range.parentElement();//Gets the current element
var copy = document.body.createTextRange();
copy.moveToElementText(srcele);
for (cursor = 0; copy.compareEndPoints("StartToStart", range) < 0; cursor++) {
 copy.moveStart("character", 1);//By changing the cursor position, we are actually recording the number of cursors }
}

Bind cursor change events to the document. Used to record cursor positions.
This will give you the DIV cursor position.
function moveEnd(obj) {
lyTXT1.focus();
var r = document.selection.createRange();
//Because we are not moving the cursor from the current position (like the textbox is from 0), we need to get the current cursor position, and then we can calculate how many bits to move, so we can move the cursor to the desired position
r.moveStart('character', lyTXT1.innerText.length - cursor);
r.collapse(true);
r.select();
}

From the above we can move the cursor in DIV to the end
A complete example
<button type="button" onclick="document.getElementById('test').focus(); insertHtmlAtCaret('<b>INSERTED</b>');"> Insert the character </button>
<div contentEditable="true" style="height:50px; border:2px solid red;" id="test"> </div>
 
function insertHtmlAtCaret(html) {
var sel, range;
if (window.getSelection) {
// IE9 and non-IE
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
// Range.createContextualFragment() would be useful here but is
// non-standard and not supported in all browsers (IE9, for one)
var el = document.createElement("div");
el.innerHTML = html;
var frag = document.createDocumentFragment(), node, lastNode;
while ( (node = el.firstChild) ) {
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
// Preserve the selection
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
} else if (document.selection && document.selection.type != "Control") {
// IE < 9
document.selection.createRange().pasteHTML(html);
}
}

Take another example based on jquery

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<title>contenteditable</title>
<style>
*{
 margin:0;padding:0;
}
.im-message-area{
 width:98%;
 padding:2px;
 height:75px;
 border:#000 solid 1px;
 background:#fff;
 font:12px/20px arial,"5b8b4f53";
 word-wrap:break-word;
 overflow-y:auto;
 line-height:1;
}
.ul{display:none;}
.ul li{
 background-color:#CCC;
 width:50px;
}
</style>
<script language="javascript" type="text/javascript">
function inimage(text){
 var obj= $(".im-message-area")[0];
 var range, node;
 if(!obj.hasfocus) {
  obj.focus();
 }
    if (window.getSelection && window.getSelection().getRangeAt) {
        range = window.getSelection().getRangeAt(0);
  range.collapse(false);
        node = range.createContextualFragment(text);
  var c = node.lastChild;
        range.insertNode(node);
  if(c){
   range.setEndAfter(c);
   range.setStartAfter(c)
  }
  var j = window.getSelection();
  j.removeAllRanges();
  j.addRange(range);
 
    } else if (document.selection && document.selection.createRange) {
        document.selection.createRange().pasteHTML(text);
    }
}
$(document).ready(function(){
 $('#button').click(function(){
  $('.ul').show();
 })
 $('.ul li').each(function(){
  $(this).click(function(){
   inimage($(this).text());
  })
 })
});
</script>
</head>
<body>
 <div contenteditable="true" id="im_message_area" class="im-message-area"><br></div>
 <a href="javascript:void(0)" id="button"> button </a>
 <ul class="ul">
  <li>( smile )</li>
  <li>( cry )</li>
  <li>( le )</li>
 </ul>
</body>
</html>


Related articles: