2

I want a button to be pushed when the user presses ctrl+enter in JavaScript. How can I achieve this? When using the below code and pressing ctrl, nothing happens. I'm also not sure how to use two keys at once.

document.addEventListener('keypress', (event) => {
  const keyName = event.key;

  alert('keypress event\n\n' + 'key: ' + keyName);
});
8
  • developer.mozilla.org/en-US/docs/Web/Events/keypress Commented Nov 10, 2017 at 14:24
  • A web search on this would turn up lots and lots of results. Stackoverflow isn't a "how to" tutorial service Commented Nov 10, 2017 at 14:27
  • I looked up 'How to implement keyboard shortcuts in html5` and it was a bunch of answers that used deprecated features. Commented Nov 10, 2017 at 14:33
  • highly doubt they are deprecated. SHow what you tried Commented Nov 10, 2017 at 14:40
  • Even if you saw deprecated features, you can still look into the documentation and see what alternatives are avalable (The link provided in the first comment) Commented Nov 10, 2017 at 15:00

1 Answer 1

6

The below code seems to work just fine. If anyone has a better solution feel free to answer!

document.addEventListener('keydown', (event) => {
    if(event.ctrlKey && event.key == "Enter") {
    alert("Ctrl+Enter key pressed");
  }
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.