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.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
HTML
JavaScript
Take a look at the
KeyboardEvent
constructor. You could use it like this: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 returnnull
if it can't find the element and you can't read properties fromnull
).You have to wait until the elements are loaded. Of course, you could create a function and call it in an
onclick
inline handler: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.
You can trigger any
event
by it'scode
that isevent.code