how can I position the cursor pointer in front of the text in the following script

2

The problem is that the cursor is not positioned in front of the text, but it is returned to the beginning. with the 'focus' event that does not happen, but I want it to work with the 'keyup' event

let textarea = document.querySelector('#textarea')

function funcion()
{
  textarea.innerHTML = textarea.innerText.replace(/@[a-zA-Z0-9_]+/gi, '<a href="https://www.dominio.com/?user=$&">$&</a>')
}

textarea.addEventListener('keyup', funcion)
<div id="textarea" contenteditable="true" style="height: 100px; padding: 10px; border: 1px solid #000"></div>
    
asked by Jorge 16.05.2018 в 22:00
source

2 answers

0
document.getElementById("textarea").focus();

add this code you should walk anything do not hesitate to consult

    
answered by 16.05.2018 в 22:03
0

Look at this option by adding a function that keeps the cursor in position after adding the text to the div, it belongs to this answer

let textarea = document.querySelector('#textarea')

function funcion()
{
  textarea.innerHTML = textarea.innerText.replace(/@[a-zA-Z0-9_]+/gi, '<a href="https://www.dominio.com/?user=$&">$&</a>')
  setCursorToEnd(textarea)
}

textarea.addEventListener('keyup', funcion)

function setCursorToEnd(ele)
  {
    var range = document.createRange();
    var sel = window.getSelection();
    range.setStart(ele, 1);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
    ele.focus();
  }
<div id="textarea" contenteditable="true" style="height: 100px; padding: 10px; border: 1px solid #000"></div>
    
answered by 16.05.2018 в 22:38