6

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?

Huangism
  • 16,278
  • 7
  • 48
  • 74
sak
  • 2,612
  • 24
  • 55

2 Answers2

2

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.

Surely
  • 1,649
  • 16
  • 23
  • `selectionStart` and `selectionEnd` are definitely way to go, but you have to be sure there are no custom selection in textarea. – borisano May 06 '15 at 16:19
  • @borisano yup, you are right, I just think of it. If there is nothing should be selected after the operation, set selectionStart=selectionEnd. If you want to select anything surrounded by the paren, change accordingly. And also, no sure what will happen if selectionStart > selectionEnd... – Surely May 06 '15 at 16:48
2

You can use selectionStart prop as described here to store and then reset cursor position

var cursorPosition = $('#myTextarea').prop("selectionStart");

Then use something like this to set cursor position

Community
  • 1
  • 1
borisano
  • 1,270
  • 1
  • 16
  • 28