Replace no `contenteditable` does not play the end pro pointer

Asked

Viewed 24 times

0

I’m trying to replace contenteditable, it replaces but does not play the pointer pro end, always keeps at the beginning. I did not know contenteditable yet and did not find anything 'simple' that works.

The same example in the element input works properly, but in contenteditable happens this 'problem' - I don’t know if something is missing...

The idea is to replace a few words and keep the cursor at the typing point.

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>

<div class="elemento" contenteditable="true">
  foo bar
</div>

  • If you want to delegate complexity to something already done, use the library Rangy. It is worth mentioning that it has compatibility for several browsers, including the bad IE.

1 answer

0

For this you can use the object Range and position you where you wish.
Reference https://developer.mozilla.org/en-US/docs/Web/API/Range

Here 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>
<div id="texto" contenteditable="true">
  Isso é um teste com foo no texto
</div>

<button id="botao">Posicionar</button>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.