I’m trying to find a basic example of the use of initKeyboardEvent()
. Ideally, I want to create a keyboard event where when the enter button is pressed when a user is typing in one input field, another input field will be shown using jQuery. Does anyone know where I can find a basic understandable example of using initKeyboardEvent()
?
Advertisement
Answer
initKeyboardEvent was originallly initKeyEvent, there is a working example at MDN: https://developer.mozilla.org/en-US/docs/DOM/event.initKeyEvent and here: http://www.howtocreate.co.uk/tutorials/javascript/domevents.
I’m sure you can find many examples through a web search: “javascript initkeyevent” and “javascript initKeyboardEvent”. Likely you will need to test for support to determine which to use.
Note also that initKeyboardEvent will be deprecated in DOM 4 (draft) in favour of Event constructor syntax, suggested in DOM 3 and implemented in DOM 4 (draft).
A simple feature test might be something like:
// Test for Event constructor
if (typeof Event != 'undefined') {
var x, evt;
try {
x = new Event('keyboardEvent');
} catch(e) {
x = void 0;
}
}
// test to see which method to use
if (typeof x != 'undefined') {
alert('Use Event constructor');
} else if (document.createEvent) {
evt = document.createEvent('KeyboardEvent');
if (evt && evt.initKeyboardEvent) {
alert('Use initKeyboardEvent');
} else if (evt && evt.initKeyEvent) {
alert('Use initKeyEvent');
}
}
But for the time being it will likely be best to test for and use DOM 2 createEvent with initKeyEvent or initKeyboardEvent as appropriate.
Note that Firefox 14 doesn’t seem to support initKeyboardEvent but does support the Event constructor and initKeyEvent, IE 9 is the opposite and doesn’t support initKeyEvent or the Event constructor, but does support initKeyboardEvent.