4

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?

Christian
  • 27,509
  • 17
  • 111
  • 155
shiva8
  • 2,142
  • 2
  • 19
  • 24

3 Answers3

5

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

Christian
  • 27,509
  • 17
  • 111
  • 155
3
$("#editor").keyup(function(){
    $(this).html($(this).html().replace(/@/g, "<div>Hello</div>"));
});
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
1

Now that you fixed that problem. To move the blinker use Selection object. Create a selection from and to the point you want your blinker goes.

Mohsen
  • 64,437
  • 34
  • 159
  • 186