onclick - Javascript Trigger keypress on mouse click WITHOUT Jquery - Stack Overflow

I found many results for this on this website but they all seem to use Jquery. I really need to know ho

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.

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.

Share Improve this question asked Jul 1, 2017 at 6:22 HasenHasen 12.4k29 gold badges85 silver badges140 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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.

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);
}

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>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745603183a4635522.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信