2

I am trying to insert text at caret position but I don't receive correct position once I insert emoji in the text.

I have created fiddle HERE

I am using below emoji jquery plugin

HTML of my page is as below.

<textarea id="message_rule"></textarea>
<br/><br/>
<div class="dropdown">
    <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        Select Tag
    </button>
    <div class="dropdown-menu" aria-labelledby="dropdownMenuButton" style="">
        <a class="dropdown-item" href="#" onclick="insertAtCaret('message_rule', '[%NAME%]');return false;">Name</a>
        <a class="dropdown-item" href="#" onclick="insertAtCaret('message_rule', '[%FIRST_NAME%]');return false;">First Name</a>
        <a class="dropdown-item" href="#" onclick="insertAtCaret('message_rule', '[%LAST_NAME%]');return false;">Last Name</a>
    </div>
</div>

I have tried solutoin given HERE, that also works only with text. Once I insert emoji the solution don't work.

My solution works perfect if the I insert only text. If I add any emoji in that, it stops working for positions after emoji.

Javascript

$(document).ready(function() {    
    $("#message_rule").emojioneArea({
        pickerPosition: "bottom"
    });
});

function insertAtCaret(myField,html) {
    var sel, range;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            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);
            if (lastNode) {
                range = range.cloneRange();
                range.setStartAfter(lastNode);
                range.collapse(true);
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
    } else if (document.selection && document.selection.type != "Control") {
        document.selection.createRange().pasteHTML(html);
    }
}
  • Looks like you're not saving the selection before the element loses focus. So, when you click the `select tag` button, it loses focus, and when you go to insert the text, it just starts at the beginning because the selection was never saved or restored. This functionality is built into the emoji picker, when is why it works [somewhat] properly. – silencedogood Mar 20 '20 at 13:51

0 Answers0