When I press space, I need the cursor to go to the correct position in the editable div

1

I need a lot of pressure when I press the cursor position correctly, that is, if you type test in the middle of the text, it stays in the middle of the text instead of going to the end. Thank you 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> 
    
asked by anonymous 07.10.2018 / 08:37

0 answers