1

I found many results for this on this website but they all seem to use Jquery. I really need to know how to do it without Jquery. What I want is to click a button and have the keystroke for example ALT+N or CTRL+G triggered. Thanks.

3 Answers 3

2

Take a look at the KeyboardEvent constructor. You could use it like this:

document.addEventListener('DOMContentLoaded', function () {
  document.getElementById('alt-n').addEventListener('click', function () {
    // create a new keyboard event
    var event = new KeyboardEvent('keydown', {
      key: 'n',
      altKey: true
    });
    // dispatch the alt+n key press event
    document.dispatchEvent(event);
  });

  document.getElementById('ctrl-g').addEventListener('click', function () {
    // create a new keyboard event
    var event = new KeyboardEvent('keydown', {
      key: 'g',
      ctrlKey: true
    });
    // dispatch the ctrl+g key press event
    document.dispatchEvent(event);
  });

  // listen for any key presses
  document.addEventListener('keydown', function (e) {
    if (e.altKey || e.ctrlKey) {
      // alt or ctrl is pressed
      console.log('Key: ' + e.key + '; alt pressed: ' + e.altKey + '; ctrl pressed: ' + e.ctrlKey);
    }
  });
});
<button id="alt-n">alt+n</button>
<button id="ctrl-g">ctrl+g</button>

Edit

When the browser parses your HTML and reaches a <script> tag, it immediately executes the JavaScript in it. It can however happen, that the rest of the document is not loaded yet.

This means that some of the HTML elements in the page don't exist yet, and you can't access them in JavaScript (document.getElementById will return null if it can't find the element and you can't read properties from null).

You have to wait until the elements are loaded. Of course, you could create a function and call it in an onclick inline handler:

function dispatchAltN () {
  var event = new KeyboardEvent('keydown', {
    key: 'n',
    altKey: true
  });
  document.dispatchEvent(event);
}

document.addEventListener('keydown', function (e) {
  if (e.altKey || e.ctrlKey) {
    // alt or ctrl is pressed
    console.log('Key: ' + e.key + '; alt pressed: ' + e.altKey + '; ctrl pressed: ' + e.ctrlKey);
  }
});
<button onclick="dispatchAltN();">alt+n</button>

However, you should not use inline JavaScript.

Fortunately, the browser fires an event when it is done loading the contents of the page. This event is called DOMContentLoaded.

When you wait for the browser to first fire the event, you can be sure that you can access all elements in the DOM.

Sign up to request clarification or add additional context in comments.

7 Comments

Getting the error "Uncaught TypeError: Cannot read property 'addEventListener' of null" with this.
I guess this is because the DOM elements haven't loaded yet when your JavaScript is executed. You have to listen for the DOMContentLoaded event. I will edit my answer to use this event.
No, there is no support for KeyboardEvent in IE. developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/…
What do you mean by shortcuts? You don't need KeyboardEvent for that. And yes, IE doesn't support it, you'd have to use initKeyboardEvent.
Ok it works now, thanks. One query though, I have a shortcut key set to trigger a function in my Mac's system but this program doesn't trigger it? Actually pressing ALT+N seems to be different to this code triggering ALT+N.....?
|
1

HTML

<button onClick="myFunction()">Click me</button>

JavaScript

function myFunction(){
var k = new Event("keydown");
k.key="a"; //Change this value for different keys
document.dispatchEvent(k);
}

1 Comment

Is that just to press the key A? How to press two keys together like in my question? e.g. CTRL+ESCAPE?
0

You can trigger any event by it's code that is event.code

<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="style.css">
  <script>
    var ev = new Event('keydown');
    ev.code = 110; // change this code to specific event code to trigger it

    function Load() {

      var button = document.getElementById('btn');
        // Listen for the event.
      button.addEventListener('keydown', function(e) {
        if (e.code === 110) {
          alert('Successfully triggered ALT + N');
        }
        // write your logic here
      }, false);
    }

    function dispatchKeypress(e) {

      e.preventDefault();

      // Dispatch the event.
      e.target.dispatchEvent(ev);

    }
  </script>
</head>

<body onload="Load()">
  <button onclick="dispatchKeypress(event)" id="btn">Button</button>
</body>

</html>

1 Comment

Thanks. But does that really press ALT+N or just "N"? 110 seems to just be 'N'. How would you press ESCAPE and ALT?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.