What is the best way to disable focus on a Textarea or Input on a keydown?

Viewed 418

I want a user to be able to use a textarea and control the textarea with a keydown. There seems to be a conflict with a detedction of a keydown when the textarea is focused on/ being used. Is there a good solution?

Psuedo Code:

 keydown(function(event) {
    if (event.which == 11) {
        $(TextArea).focusout();
        SwitchTextAreaFunction();
        $(TextArea).focus();
      }
    }
1 Answers

I think you want something like this.

document.addEventListener('keydown', (e) => {
  const myTextArea = $("#myTextArea");
  if (e.keyCode === 13 /* 13=enter */ ) {
    if (!myTextArea.is(":focus")) {
      // textarea has no focus
      e.preventDefault();
      myTextArea.focus();
    } else {
      // textarea has focus
      myTextArea.blur();
    }
  }
})
<textarea id="myTextArea">TextArea</textarea>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related