Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / HTML

onkeydown — handling a key press

The onkeydown attribute contains JavaScript code that handles the keydown event. It lets you respond to a key press; the event object provides event data. It is not a Boolean attribute.

Version: WHATWG HTML Living Standard; index snapshot date recorded separately

Syntax

onkeydown="JavaScript statements"

onkeydown is an HTML event handler attribute for keydown. Its value is a JavaScript function body, not an event name or a URL. Merely writing a function name without calling it does not execute that function.

Inside the attribute code, the event parameter provides the event. The HTML attribute onkeydown="…" and the JavaScript property element.onkeydown configure the same handler mechanism; assigning a new function to the property replaces the existing handler.

return false cancels the event's default action if the event is cancelable, but does not stop its propagation. Content Security Policy can block handlers written directly in attributes. Never insert untrusted text into the attribute as code.

Examples

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>onkeydown example</title>
<button type="button" onkeydown="if (event.key === 'Enter') document.getElementById('result').textContent = 'Enter';">Focus here; press Enter</button>
<p id="result" aria-live="polite">Waiting</p>
</html>

Result

Enter

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources