Categories
JavaScript Answers

How to capture ctrl+z key combination in JavaScript?

Spread the love

Sometimes, we want to capture ctrl+z key combination in JavaScript.

In this article, we’ll look at how to capture ctrl+z key combination in JavaScript.

How to capture ctrl+z key combination in JavaScript?

To capture ctrl+z key combination in JavaScript, we can listen to the keydown event.

For instance, we write

document.addEventListener("keydown", (event) => {
  if (event.ctrlKey && event.key === "z") {
    console.log("Undo!");
  }
});

to listen for the keydown event on the page with document.addEventListener.

In the event handler callback, we check if the ctrl key is pressed with event.ctrlKey.

And we check if the z key is pressed with event.key === "z".

If they’re both true, then ctrl+z is pressed.

Conclusion

To capture ctrl+z key combination in JavaScript, we can listen to the keydown event.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *