0

How can i set pointer position? I tried the most famous solution from this topic: Set keyboard caret position in html textbox But this solutions work just in input...

This is the code:

$(document).ready(function(){
 $("#asd").keypress(function(){
  //set cursor to a position
 })
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head><body>

<pre id="asd" contenteditable="true" >
asd
</pre>

</body>
</html>
Community
  • 1
  • 1
Bakos Bence
  • 243
  • 5
  • 7

1 Answers1

2

Like this:

function setCursor(pos) {
    var el = document.getElementById("asd");
    var range = document.createRange();
    var sel = window.getSelection();
    range.setStart(el.childNodes[0], pos);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
    el.focus();
}

$(document).ready(function(){
 $("#asd").keypress(function(){
  setCursor(4);
 })
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head><body>

<pre id="asd" contenteditable="true" >
asd
two
</pre>

</body>
</html>
Ultrazz008
  • 1,678
  • 1
  • 13
  • 26