0

I've created an editable div and want to change the text inside it, format, and more. However, in doing this, I am using $("#tag").text("aaaaaa") and when doing this the cursor is moved to the starting position. I need the cursor to be in the final position when edited by .text in jquery.

HTML

<div contenteditable="true" id="tag" name="tag"><span class="spanTag"></div>

JQuery

      $("#tag").on('input',function () {

      $("#tag").text("asdfasdf");

    var range,selection;
    if(document.createRange) {
        range = document.createRange();//Create a range (a range is a like the selection but invisible)
        range.selectNodeContents($("#tag"));//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        selection = window.getSelection();//get the selection object (allows you to change selection)
        selection.removeAllRanges();//remove any selections already made
        selection.addRange(range);//make the range you have just created the visible selection
    } });
Taplar
  • 24,788
  • 4
  • 22
  • 35
  • Possible duplicate of [How to set caret(cursor) position in contenteditable element (div)?](https://stackoverflow.com/questions/6249095/how-to-set-caretcursor-position-in-contenteditable-element-div) – imvain2 May 08 '19 at 18:52
  • It's possible to do this same example with append ("Content"), I tested it here and it did not work – Renan Angelini Ferrari May 08 '19 at 21:08

0 Answers0