1
I really need that when I press space the cursor is positioned correctly, that is, if you type test in the middle of the text it is in the middle of the text instead of going to the end. Thanks in advance
<html>
<head>
<script>
function ret_pos(element)
{
var caretOffset = 0;
var range = window.getSelection().getRangeAt(0);
var preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(element);
preCaretRange.setEnd(range.endContainer, range.endOffset);
caretOffset = preCaretRange.toString().length;
document.getElementById('po').innerText = caretOffset;
return caretOffset;
}
function highlight(event,word)
{
var tecla = event.keyCode;
if (tecla == 32)
{
//cath the contenteditable element
var editor = document.getElementById("editor");
//cath the cursor position
var cursor_position=ret_pos(editor);
var html_text = editor.innerHTML;
var re = new RegExp(word, 'g');
html_text = html_text.replace(re, '<b>'+word+'</b>');
editor.innerHTML=html_text;
/*agora manda pro fim do texto, mas queria que ficasse onde está,
sem o bloco abaixo vai para o início*/
var range = document.createRange();
range.selectNodeContents(editor);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
}
</script>
<body>
<div id="editor" onkeypress="highlight(event,'test');" style="position:absolute; display:block; width:50%; height:50%; left:5%; border-style:solid; border-width:1px;" contenteditable>
my text, please insert the word test here and press space.
</div>
<div style="position:absolute; width:3%; height:6%; left:36%; top:55%; border-style:solid; border-width:0.3px;">
<text id="po">...</text>
</div>
</body>
</html>
And what would be correct form??
– LeAndrade
The cursor go to the position it was before the replacement, ret_pos informs this position. Thank you
– Luis Miguel