ContentEditable=true Not working correctly [Blaze]


#1

Hi Everyone, I want to implement the feature in which there is an option for adding hashtags in the text input field. For this, I have used the paragraph tag as a contentEditable true.

The issue is

  • I need to paste HTML at the cursor position but it’s not working like expected.

anchorOffset is always 0 in window.getSelection(), when tried to paste the HTML, its always putting the HTML content at the first position. is there any other way for doing the same thing

Any help would be appreciated.

function pasteHtmlAtCaret(html, selectPastedContent) {
    var sel, range;
    console.log(window.getSelection());
    if (window.getSelection()) {
        // IE9 and non-IE
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt($('#post_content').prop('selectionStart'));
            range.deleteContents();

            // Range.createContextualFragment() would be useful here but is
            // only relatively recently standardized and is not supported in
            // some browsers (IE9, for one)
            var el = document.createElement("span");
            el.innerHTML = html;
            var frag = document.createDocumentFragment(), node, lastNode;
            while ( (node = el.firstChild) ) {
                lastNode = frag.appendChild(node);
            }
            var firstNode = frag.firstChild;
            range.insertNode(frag);
            
            // Preserve the selection
            if (lastNode) {
                range = range.cloneRange();
                range.setStartAfter(lastNode);
                if (selectPastedContent) {
                    range.setStartBefore(firstNode);
                } else {
                    range.collapse(true);
                }
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
    } else if ( (sel = document.selection) && sel.type != "Control") {
        // IE < 9
        var originalRange = sel.createRange();
        originalRange.collapse(true);
        sel.createRange().pasteHTML(html);
        if (selectPastedContent) {
            range = sel.createRange();
            range.setEndPoint("StartToStart", originalRange);
            range.select();
        }
    }
}