What I'm trying to do is run a script (JS) that selects a test box. It's ID field name is JMan. Once it selects that field I am trying to programmatically have my code perform the key combination ALT+0 and then delay itself for 5 seconds. By the way I'm performing this in the 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);
The detection event handler is a no-frills method of detecting Alt-0. You might consider more sophisticated checking to do things like determine if another key was pressed between the Alt and 0 (i.e this code will treat Alt-1-0 as if it were Alt-0 or Ctrl-Alt-0 as if it were Alt-0)(At least it checks if you hold down Alt-0). This is mainly because key events differ considerably between browsers and I wanted to make something that will hopefully work on the majority.
The button in this example fires a minimal "Alt-0" event designed for the event handler to catch (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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With