Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refocus where it was in textfield after pressing a button in Javascript?

Tags:

javascript

There is a javascript button that if it's pressed, it inserts a string. Then after pressing a button, focus will back to textfield. However, with my code, always focus goes back to end of the string, not where it was.

For example now focus is between 3 and 4.

enter image description here

and after pressing "ā", focus goes to after 7.

enter image description here

But I want the focus go to between "ā" and 4.

Here is my code

<script>
function addTF(str)
{
    var area = document.getElementById('pronounce');
    area.value = area.value.substr(0, area.selectionStart)
    + str
    + area.value.substr(area.selectionStart);
    area.focus();
}
</script>

<input type="text" id="pronounce" name="pronounce">
<input type="button" value="ā" onClick="addTF(this.value)">

So how can I achieve this? Thank you.

like image 924
Tieria Avatar asked Sep 17 '25 15:09

Tieria


1 Answers

You can set the selectionStart and selectionEnd of the text field to restore the previous caret position:

var addTF;

window.addEventListener('load', () => {
    var area = document.getElementById('pronounce');
    var lastPos = 0;
    
    area.addEventListener('change', () => lastPos = area.selectionStart);
    area.addEventListener('click', () => lastPos = area.selectionStart);

    addTF = function(str) {
        area.value = area.value.substr(0, area.selectionStart) + str + area.value.substr(area.selectionStart);
        lastPos++;
        area.selectionStart = lastPos;
        area.selectionEnd = lastPos;
        area.focus();
    }
});
<input type="text" id="pronounce" name="pronounce">
<input type="button" value="ā" onClick="addTF(this.value)">
like image 123
Hao Wu Avatar answered Sep 20 '25 06:09

Hao Wu