Search code examples
javascriptonclickkeypress

Javascript Trigger keypress on mouse click WITHOUT Jquery


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.


Solution

  • 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.