Material Box

Material Box

WEB Design & Material Images

JavaScript - Key Press and Hold Event


A basic JavaScript code example for detecting when a specified key is pressed and held.

The HTML has a <div> tag with ID "target" that can detect key presses.

The "tabindex" attribute allows focus for detecting key events. Not needed for text inputs or document.

<div id="target" tabindex="0">Press and hold the spacebar</div>

The CSS sets the size for the event target element.

#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;
	user-select: none;
	transition: 1s;
	background: #dc143c;

The target element is selected with querySelector(). The keydown event listener checks for the spacebar key code of 32.

A timer is set to trigger the hold event after a duration without the key being released.

The keyup listener clears the timer when released.

// Target Element
let target = document.querySelector('#target');

// Event timer ID
let eventTimerId;

// Key Down Event
target.addEventListener('keydown', () => {
	// Check for spacebar
	if (event.keyCode == 32) {
		// Prevent default action
	 	// Set timer for hold duration 
		eventTimerId = setTimeout(function () {
			// Code when hold event triggers
			if (window.getComputedStyle(target).borderRadius !== '0%') { = '0%';
			} else { = '50%';

		}, 1000);

// Key Up Event
target.addEventListener('keyup', () => {
	// Check for spacebar 
	if (event.keyCode == 32) {
		// Clear event timer

JavaScript - Key Press and Hold Event

TitleJavaScript - Key Press and Hold Event