Replace in 'contenteditable' does not throw the pointer to the end

0

I'm trying to give a replace in contenteditable , it replaces but does not throw the pointer to the end, it always keeps on startup. I did not know contenteditable yet and found nothing 'simple' that works.

The same example in element input works correctly, but in contenteditable this problem happens - I do not know if something is missing ...

The idea is to replace some words and keep the cursor at the point of typing.

jsfiddle

$(".elemento").on('input', function( e )
{
   	content = $(this).html().replace(/foo/g, 'bar');
   	$(this).html( content )
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="elemento" contenteditable="true">
  foo bar
</div>
    
asked by anonymous 11.05.2018 / 11:33

1 answer

0

For this you can use the object Range and position it where you want. Reference link

Here's an example:

$('#botao').click(function () {
    var div = $("#texto");
    var content = $(div).html();
    var range = document.createRange();
    var sel = window.getSelection();
    // posição do texto
    var pos = content.indexOf("foo");
    // substitiu
    content = content.replace(/foo/g, 'bar');
   	$(div).html(content);
    // cria um range, selecionando o primeiro conteúdo do div, na posição do texto "foo". 
    range.setStart(texto.childNodes[0], pos);
    range.collapse(true);
    sel.removeAllRanges();
    // posiciona no range
    sel.addRange(range);
    div.focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="texto" contenteditable="true">
  Isso é um teste com foo no texto
</div>

<button id="botao">Posicionar</button>
    
11.05.2018 / 14:13