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:
User types an @
inside #editor
keyup
event picksup the @
position
$('#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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With