To utilize the KeyboardEvent
as a constructor, you can implement the following functionality using vanilla JavaScript
var event = new KeyboardEvent('keypress', {shiftKey: true});
element.dispatchEvent(event);
Where element
is the designated target element
A more extensive approach:
function simulateKeyPress(target, /*optional*/ bubbleUpwards, /*optional*/ eventType) {
var options = {shiftKey: true};
if (bubbleUpwards) options.bubbles = true;
if (!eventType && eventType !== 0) eventType = -1;
if ((eventType & 1) === 1) target.dispatchEvent(new KeyboardEvent('keydown', options));
if ((eventType & 2) === 2) target.dispatchEvent(new KeyboardEvent('keypress', options));
if ((eventType & 4) === 4) target.dispatchEvent(new KeyboardEvent('keyup', options));
}
simulateKeyPress.keydown = 1;
simulateKeyPress.keypress = 2;
simulateKeyPress.keyup = 4;
// For example, to trigger a keypress that bubbles up through the DOM
simulateKeyPress(document.body, true, simulateKeyPress.keypress);