KeyboardEvent
Creates a new KeyboardEvent representing a keyboard interaction
Syntax
new KeyboardEvent(type, options?)Parameters
| Parameter | Type | Description |
|---|---|---|
| type | string | The type of keyboard event (keydown, keyup, keypress) |
| options | KeyboardEventInit | Options including key, code, ctrlKey, shiftKey, altKey, metaKey |
Return Value
A new KeyboardEvent object
Examples
document.addEventListener('keydown', (e: KeyboardEvent) => {
console.log('Key:', e.key, 'Code:', e.code)
})document.addEventListener('keydown', (e: KeyboardEvent) => {
if (e.ctrlKey && e.key === 's') {
e.preventDefault()
console.log('Save triggered')
}
})function simulateKeyPress(el: Element, key: string) {
const event = new KeyboardEvent('keydown', {
key,
bubbles: true,
cancelable: true
})
el.dispatchEvent(event)
}Understanding KeyboardEvent
The KeyboardEvent method in JavaScript creates a new KeyboardEvent representing a keyboard interaction. It belongs to the Event object and is one of the most widely used methods for working with event values in modern JavaScript and TypeScript applications.
The method signature is new KeyboardEvent(type, options?). It accepts 2 parameters: type, options. When called, it returns a new keyboardevent object. Understanding when and how to use KeyboardEvent() helps you write more expressive, readable code.
Common use cases for KeyboardEvent include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like event-addeventlistener, event-preventdefault, event-mouseevent, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for KeyboardEvent is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
EventTarget.prototype.addEventListenerRegisters an event handler of a specific event type on the EventTarget
Event.prototype.preventDefaultTells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be
MouseEventCreates a new MouseEvent representing a mouse interaction
More Event Methods
Other methods in the Event object
Related Tools
More Event Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.