Material Box

Material Box

WEB Design & Material Images

JavaScript - Keyboard Input Event

JavaScript

Introducing a simple code example implementing events triggered by keyboard input in JavaScript.


In the HTML, a <div> element is assigned the ID 'target' to detect keyboard inputs.

Setting 'tabindex' allows focusing and enables key input events.

While this example uses a <div> tag as the target, 'tabindex' is unnecessary when targeting text input forms or the entire document.

<div id="target" tabindex="0">Please press any key</div>

In CSS, the size for the event target is set.

The pseudo-class 'focus' specifies the outline displayed upon focusing when the element is clicked.

#target {
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 24px;
	padding: 10px;
	color: white;
	width: 250px;
	height: 250px;
	border-radius: 50%;
	text-align: center;
	cursor: pointer;
	background-color: #2f4f4f;
}

/* Specify the outline when focused */
#target:focus {
	outline: 2px solid #000fff;
}

The element is specified using querySelector(), and 'addEventListener()' is used to detect the 'keydown' event, indicating that a key has been pressed.

This code example displays the pressed key's name and code within the target element when the event is detected.

Additionally, 'keyup' clears the displayed key code and name when the key is released.

// Output Area
let target = document.querySelector('#target');

target.addEventListener('keydown', (event) => {
	// Prevent default behavior
	event.preventDefault();
	// Output the pressed key code within the target element
	target.innerHTML = event.keyCode + '<br>' + event.key;
});

target.addEventListener('keyup', () => {
	// Clear the displayed key code
	target.innerHTML = 'Please press any key';
});

JavaScript - Keyboard Input Event

TitleJavaScript - Keyboard Input Event

CategoryJavaScript

Created

Update

AuthorYousuke.U