Solution Timeline

All versions (edits) of solutions to Insert given string in a "contenteditable" div at cursor position appear below in the order they were created. Comments that appear under revisions were those created when that particular revision was current.

To see the revision history of a single solution (with diffs), click on the solution number (ie. "#1") in the upper right corner of a solution revision below.

← Bounty Expand all edits

Try in JS part:

$( "#emojis span" )
.on( "click", function() {
$( "#input" )
.append($( this ).text());
} )

Or something like this:

Winning solution Tipped

I got one solution here. Please update it according to your requirement. Thanks.

var caretPos = 0;

function addEmoji(event) {
  this.insertIntoFormula(`<span>${event.target.innerHTML}</span>&nbsp;`, caretPos);
 }
function insertIntoFormula(specialChar, pos) {
     const textarea = document.getElementById('field-content');
      let value = textarea.innerHTML;
      let beforeText = value.slice(0, pos);
   let afterText = value.slice(pos);

 value = beforeText + specialChar + afterText;
  textarea.innerHTML = value;
}

function getCaretCharacterOffsetWithin(event) {
  let element = event.target;
  let caretOffset = 0;
let doc = element.ownerDocument || element.document;
let win = doc.defaultView || doc.parentWindow;
let sel;
if (typeof win.getSelection != "undefined") {
sel = win.getSelection();
if (sel.rangeCount > 0) {
  let range = win.getSelection().getRangeAt(0);
  let preCaretRange = range.cloneRange();
  preCaretRange.selectNodeContents(element);
     console.log('Range: ' + preCaretRange);
  preCaretRange.setEnd(range.endContainer, range.endOffset);
  caretOffset = preCaretRange.toString().length;
}
 } else if ( (sel = doc.selection) && sel.type != "Control") {
let textRange = sel.createRange();
let preCaretTextRange = doc.body.createTextRange();
preCaretTextRange.moveToElementText(element);
preCaretTextRange.setEndPoint("EndToEnd", textRange);
caretOffset = preCaretTextRange.text.length;
}
console.log('Caret: ' + caretOffset);
caretPos = caretOffset;
 }