Redirecting Ctrl+A with JavaScript

Apr 20, 2014

I needed to catch Ctrl+A and redirect it to copy the content of a specific element. This does exactly that:

document.addEventListener('keydown', function (event) {
  if(event.ctrlKey && event.keyCode == 65) {
    var range = document.createRange();

What it does:

  • Attach a keydown handler to document to get all key presses
  • Make sure Ctrl+A have been pressed (A is keyCode 65)
  • Add a selection to an element (<main> in this case)
  • Call preventDefault to make sure the event is ignored by the browser
Back to blog