Material Box

Material Box

WEB Design & Material Images

JavaScript - Space Key Input Event

JavaScript

Introducing a simple code example in JavaScript that implements events triggered by pressing the space key.


In the HTML, a <div> element with the ID 'target' is used to detect input triggered by the space key.

Setting 'tabindex' allows focusing, enabling the execution of key input events.

<div id="target" tabindex="0">Press the space 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: #000080;
}

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

The target element is specified using querySelector(), and 'addEventListener()' is used to set up the 'keydown' event, triggered when a key is pressed.
Within the key input event, it checks if the key code corresponds to the space key ('32') and implements the event accordingly.

Similarly, 'keyup' is implemented to clear the displayed content when the space key is released.

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

target.addEventListener('keydown', (event) => {
	// Prevent default behavior
	event.preventDefault();
	// Check if space key is pressed
	if (event.keyCode === 32) {
		// Output within the target element
		target.innerHTML = 'Space key is pressed';
	}
});

target.addEventListener('keyup', (event) => {
	// Check if space key is released
	if (event.keyCode === 32) {
		// Clear target display
		target.innerHTML = 'Press the space key';
	}
});

JavaScript - Space Key Input Event

TitleJavaScript - Space Key Input Event

CategoryJavaScript

Created

Update

AuthorYousuke.U