Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replaceHtmlAt using jQuery inside contentEditable div

I'm trying to achieve the following functionality:

<div id="editor" contenteditable="true">
I am some text.
</div>

$('#editor').replaceHtmlAt(start, end, string);

Use case:

  1. User types an @ inside #editor

  2. keyup event picksup the @ position

  3. $('#editor').replaceHtmlAt(position of @, position of @ + 1, "<div>Hello</div>");

Is this possible?

EDIT

I got it to work by doing this

$(this).slice(pos-1).html('<span id="mention'+pos+'">@</span>');

However I've encountered another problem. In Chrome, the caret position inside #editor moves all the way to the back... how do I restore the caret's position after '@' inside the span tags?

like image 812
shiva8 Avatar asked Jan 16 '23 10:01

shiva8


1 Answers

Dylan, although your thinking about replacing '@' is right in layman terms, we (coders) know that we can intercept and mess around with key events.

So, building on what Derek used up here, I'd do:

// @see http://stackoverflow.com/a/4836809/314056
function insertNodeBeforeCaret(node) {
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var range = sel.getRangeAt(0);
            range.collapse(false);
            range.insertNode(node);
            range = range.cloneRange();
            range.selectNodeContents(node);
            range.collapse(false);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    } else if (typeof document.selection != "undefined" && document.selection.type != "Control") {
        var html = (node.nodeType == 1) ? node.outerHTML : node.data;
        var id = "marker_" + ("" + Math.random()).slice(2);
        html += '<span id="' + id + '"></span>';
        var textRange = document.selection.createRange();
        textRange.collapse(false);
        textRange.pasteHTML(html);
        var markerSpan = document.getElementById(id);
        textRange.moveToElementText(markerSpan);
        textRange.select();
        markerSpan.parentNode.removeChild(markerSpan);
    }
}

$("#editor").keydown(function(event){
    if(event.which == 50 && event.shiftKey){ // 50 => '2' and shift+'2' => @
        event.preventDefault(); // abort inserting the '@'
        var html = $('<span>hi</span>'); // create html node
        insertNodeBeforeCaret(html[0]); // insert node before caret
    }
});​

Demo JSFiddle

like image 92
Christian Avatar answered Jan 28 '23 10:01

Christian