1

I am trying to achieve that when the user presses the reset button, the cursor positions back to the beginning of the input.

Can anyone guide me on how to achieve this?

enter image description here

function restore(){
    // here need to set the position
};
p {
  text-align:left;
  padding:10px;
  font-size: 20px;
  font-family: "Open Sans";
  border:1px black solid;
}

button{
 font-size: 25px;
}
<p contenteditable="true"></p>

<button onclick="restore()">Restore</button>
minus.273
  • 755
  • 11
  • 24
Asma Alfauri
  • 83
  • 1
  • 7
  • Is this what you are asking for ? https://stackoverflow.com/questions/512528/set-keyboard-caret-position-in-html-textbox – Jabir Feb 05 '20 at 07:50

2 Answers2

2

You can use Range and Selection objects as described in this answer:

function restore() {
  var el = document.getElementById("editable");
  var range = document.createRange();
  var sel = window.getSelection();
  range.setStart(el, 0);
  range.collapse(true);
  sel.removeAllRanges();
  sel.addRange(range);
}
p {
  text-align:left;
  padding:10px;
  font-size: 20px;
  font-family: "Open Sans";
  border:1px black solid;
}

button{
 font-size: 25px;
}
<p id="editable" contenteditable="true"></p>

<button onclick="restore()">Restore</button>
technophyle
  • 7,972
  • 6
  • 29
  • 50
1

If you can use the Input tag instead of the P tag, this code is appropriate :

function myFunction() {
  var text = document.getElementById("myInput");
  text.select();
  text.setSelectionRange(text.value.length, text.value.length)
}
button{
 font-size: 25px;
}
<input type="text" value="hello" id="myInput">
<button onclick="myFunction()">Copy text</button>
iman madani
  • 299
  • 1
  • 12