Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve cursor position on textarea text change?

I'm trying to implement a textarea which automatcally inserts close parens in React, but whenever I modify the textarea's value property, the cursor jumps to the end of the text being edited.

Here's my onChange function:

    //on change
    function(event) {

        var newText =  event.target.value

        var cursorPosition = getCursorPosition(event.target)
        if(lastCharacterWasParen(newText, cursorPosition)){
            newText = newText.slice(0, cursorPosition) + ')' + newText.slice(cursorPosition)
        }

        this.setProps({text: newText}})

    }

This successfully inserts the paren, but how do I preserve the cursor position?

like image 889
sak Avatar asked Oct 20 '22 12:10

sak


1 Answers

I am doing similar things before.

The way to change the cursor position is using: evt.target.selectionEnd

In your case, you can record down the selectionEnd before inserting, and after inserting, set the selectionEnd to the position it should be.

like image 172
Surely Avatar answered Oct 24 '22 12:10

Surely