I ...">

ReplaceHtmlAt using jQuery inside contentEditable div

I am trying to perform the following functions:

<div id="editor" contenteditable="true"> I am some text. </div> $('#editor').replaceHtmlAt(start, end, string); 

Use Case:

  • A @ custom types inside #editor

  • keyup event selects position @

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

Is it possible?

EDIT

I earned by doing this

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

However, I ran into another problem. In Chrome, the carriage position inside #editor moves completely backward ... how do I restore the carriage position after the "@" inside span tags?

+4
source share
3 answers

Dylan, although your thinking about replacing "@" is fair in layman terms, we (the coders) know that we can intercept and intervene in key events.

So, based on what Derek used here, I would 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 } });​ 

JSFiddle demo

+5
source
 $("#editor").keyup(function(){ $(this).html($(this).html().replace(/@/g, "<div>Hello</div>")); }); 
+3
source

Now that you have fixed this problem. To move the flicker, use the Selection object. Create a selection from and to the point where you want your blinking icon.

+1
source

All Articles