How to create custom keyboard shortcut key combinations for text input?

Viewed 1165

I have a simple html textarea input and I'd like to type in special character combinations like %>% and <- using keyboard shortcuts like Ctrl + Shift + M and Alt + -, respectively.

Code:

<!DOCTYPE html>
<html>
<body>
<textarea id="text1" name="text1" rows="4" cols="50">
  </textarea>
</body>
</html>

What is the best way to write code for custom keyboard shortcuts using html, css, javascript, jquery, or any other framework?

2 Answers

I guess I misunderstood your question, but I rely on the best. This is a small example of creating hotkeys for textarea using event onkeyup.

  • e.ctrlKey && e.shiftKey && e.which == 77 - Ctrl + Shift + M;
  • e.altKey && e.which == 189 - Alt + -.

I advise you to read this article.

let text_area = document.querySelector('#text1');
text_area.onkeyup = function(e) {
  if (e.ctrlKey && e.shiftKey && e.which == 77) {
    this.value += "%>%";
  } else 
  if (e.altKey && e.which == 189) {
    this.value += "<-";
  } else {}
};
<!DOCTYPE html>
<html>
  <body>
    <textarea id="text1" name="text1" rows="4" cols="50"></textarea>
  </body>
</html>

I have a simple html textarea input and I'd like to type in special character combinations like %>% and <- using keyboard shortcuts like Ctrl + Shift + M and Alt + -, respectively.

You can create a function that runs conditionals that check input of your text area value -> onkeydown. Use keycodes in the conditionals and preventDefault so when those key combos are pressed, only the desired value will be input into the value using a concatenation of the value.

let textArea = document.getElementById('text1');

function keyCombos(e) {
  let evtobj = window.event ? event : e
  let val = document.getElementById('text1');
  //key combo for ctrl+M
  if (evtobj.keyCode == 77 && evtobj.shiftKey) {
    e.preventDefault();
    val.value += "%*%";
    //key combo for alt+m
  }
  else if(evtobj.keyCode == 77 && evtobj.altKey) {
    e.preventDefault();
    val.value += "->";
  }
  //continue adding conditionals in your fi else
}

document.getElementById('text1').onkeydown = keyCombos;
<!DOCTYPE html>
<html>

<body>
  <div>Press ALT + M for -> or SHIFT + M for %*%</div>
  <textarea id="text1" name="text1" rows="4" cols="50">
  </textarea>
</body>

</html>

Related