Programmatically pressing Alt 0 with JavaScript
What I am trying to do is run a script (JS) that selects the testfield. The name of this identifier is JMan
. Once it selects that field, I try to programmatically execute the code that executes the keyboard shortcut ALT+0
, and then it pauses for 5 seconds. By the way, I am doing this in IE browser.
function myFunction() {
var keyboardEvent = document.createEvent("keyboardEvent").;
document.getElementById("JMan");
}
var keyboardEvent = document.createEvent("KeyboardEvent");
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";
keyboardEvent[initMethod](
"keydown", // event type : keydown, keyup, keypress
true, // bubbles
true, // cancelable
window, // viewArg: should be window
false, // ctrlKeyArg
true, // altKeyArgenter code here
false, // shiftKeyArg
false, // metaKeyArg
48, // keyCodeArg : unsigned long the virtual key code, else 0
0 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
);
document.dispatchEvent(keyboardEvent);
source to share
The discovery event handler is a no-nonsense technique for detecting Alt-0. You might consider a more complex check to do something like determining if another key was pressed between Alt and 0 (i.e. this code will handle Alt-1-0
as if it was Alt-0
or Ctrl-Alt-0
as if it was Alt-0
) (At least at least it checks if you are holding Alt-0). This is mainly due to the fact that key events differ significantly between browsers, and I wanted to do something that will hopefully work on most.
The button in this example fires a minimal "Alt-0" event designed to capture the event handler (or you should be able to type Alt-0 into the window).
function fireAlt0() {
console.log("firing event");
window.dispatchEvent(new KeyboardEvent("keydown", { key: "0", altKey: true }));
}
function detectAlt0(event) {
if ("keydown" == event.type) { // we might want to use the same function for any of ( keydown, keypress, keyup ) events
if (event.key == "0" && event.altKey && !event.repeat) {
console.log("Open a window!");
}
}
}
window.addEventListener("DOMContentLoaded", function () {
// Use keydown because keypress won't fire for the Alt-0 combination (since it doesn't produce a visible character)
window.addEventListener("keydown", detectAlt0, false);
document.getElementById("button").addEventListener("click", fireAlt0, false);
}, false);
<button id="button">fireAlt0</button>
source to share