Home > database >  How to prevent normal cursor behavior when pressing keys in a textarea
How to prevent normal cursor behavior when pressing keys in a textarea

Time:03-29

I have the following code

 textarea#main-text-area(
        rows="1"
        ref="textArea"
        maxlength="4096"
        v-model="message"
        :placeholder="placeholder"
        @keyup="onTextAreaKeyUp"  
        @change="onChangeMessage"
        :
        v-click-outside="onTextAreaBlur"
      )

and i listen for the keyup event. I need the cursor not to move when I press up or down.

I tried to do the following but it didn't work for me as the cursor moved anyway

onTextAreaKeyUp(e) {
      if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
        e.preventDefault();
      }
    }

CodePudding user response:

Use preventDefault on the keydown event instead of keyup.

document.querySelector('textarea').addEventListener('keydown', e => {
  if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
    e.preventDefault()
  }
})
<textarea>Hello, World! Hello, World! Hello, World! Hello, World! </textarea>

  • Related