JavaScript offers keyboard events that facilitate the selection, input, and manipulation of specific types of information. These events are triggered by the action of pressing a key down and releasing it, known as key up. You can implement these events using HTML tags, JavaScript functions, or by utilizing the addEventListener method. This functionality enables keyboards to interact with user forms and various other components. The KeyboardEvent object plays a crucial role in managing these keyboard events.
Types of the keyboard event
The javascript provides the following types of events to use keyboard functionality.
- Keydown event: Keydown occurs when the key is depressed and continuously repeats if the key is depressed for an extended time.
- Keyup event: When a punctuation, numeric, or alphabetic key is pushed, then the keyup event is triggered and starts functionality.
- Keypress event: When the key is released from the user, the keyup event occurs and starts functionality. Some browsers no longer support Keypress Event.
Javascript keydown event
When a key is pressed and remains in the depressed position on the keyboard, the JavaScript keydown event is triggered within the application. This keyboard event is applicable to input values on the webpage, including forms, search fields, and various other components.
Syntax
The subsequent syntax for the key-down event illustrates the location of the keyboard key and its utilization.
- In HTML
- In Javascript
- In addEventListener event
<input type = "text" id = "input_class" onkeydown = "keyDownFunction()">
<script>
var demoObj = document.getElementById("input_class");
demoObj.onkeydown = keyDownFunction;
</script>
<script>
var demoObj = document.getElementById("input_class");
demoObj.addEventListener("keydown", keyDownFunction);
</script>
Examples
The key-down event in JavaScript incorporates an HTML element along with a corresponding JavaScript function.
Example 1
The alert section displays the customized functionality once the key-down function has been executed. The input element of the user-interactive component
<!DOCTYPE html>
<html>
<head>
<title> keydown function in javascript </title>
<style>
#datas {
color: green;
}
</style>
</head>
<body>
<h2> JavaScript keydown Method </h2>
<div id = "demoDIV" >
The javascript key-down event works after pressing the key and key in the down position on the specific tag.
</div>
<input type = "text" id = "input_class" placeholder = "write here." onkeydown = "keyDownFunction()">
<p id = "datas"> </p>
<script>
function keyDownFunction() {
alert("JavaScript keyDown function activates successfully!!!");
document.getElementById("datas").innerHTML = "JavaScript keyDown function activates successfully!!!";
}
</script>
</body>
</html>
Output
The alert dialog displays the result of the keydown event.
Example 2
The JavaScript keydown event utilizes an HTML element along with a JavaScript function. Following the execution of the keydown function, we can modify the style attribute of the container.
<!DOCTYPE html>
<html>
<head>
<title> keydown function in javascript </title>
<style>
#datas {
color: green;
}
</style>
</head>
<body>
<h2> JavaScript keydown Method </h2>
<div id = "demoDIV" >
The javascript key-down event works after pressing the key and key in the down position on the specific tag.
</div>
<input type = "text" id = "input_class" placeholder = "write here.">
<p id = "datas"> </p>
<script>
var demoObj = document.getElementById("input_class");
demoObj.onkeydown = keyDownFunction;
function keyDownFunction() {
console.log("JavaScript keyDown function!!");
document.getElementById("datas").innerHTML = "JavaScript keyDown function activates successfully!!!";
document.getElementById("demoDIV").style.width = "440px";
document.getElementById("demoDIV").style.border = "4px dotted navy";
document.getElementById("demoDIV").style.color= "orange";
}
</script>
</body>
</html>
Output
The alert dialog displays the result of the keydown event.
Example 3
The addEventListener method is utilized for handling the keydown event with JavaScript. This keydown event can operate on either individual or multiple radio buttons through the use of an input tag.
<!DOCTYPE html>
<html>
<head>
<title> keydown function in javascript </title>
<style>
#datas {
color: green;
}
</style>
</head>
<body>
<h2> JavaScript keydown Method </h2>
<div id = "demoDIV" >
The javascript key-down event works after pressing the key and key in the down position on the specific tag.
</div>
<input type = "radio" id = "input_class" placeholder = "write here."> Good
<input type = "radio" id = "input_class" placeholder = "write here."> Better
<input type = "radio" id = "input_class" placeholder = "write here."> Best
<p id = "datas"> </p>
<script>
var demoObj = document.getElementById("input_class");
demoObj.addEventListener("keydown", keyDownFunction);
function keyDownFunction() {
console.log("JavaScript keyDown function!!");
document.getElementById("datas").innerHTML = "JavaScript keyDown function activates successfully!!!";
document.getElementById("demoDIV").style.width = "440px";
document.getElementById("demoDIV").style.border = "4px dotted navy";
document.getElementById("demoDIV").style.color= "orange";
}
</script>
</body>
</html>
Output
The alert box displays the result of the keydown event.
Javascript keyup event
When a key is pressed down and remains in its original position on the keyboard, the JavaScript key-up event is triggered within the application. This keyboard event is applicable to input values across the webpage, including forms, search fields, and various other components.
Syntax
The syntax for the keyup event provided below illustrates the position of keyboard keys and their usage.
- In Html
- In Javascript
- In addEventListener event
<input type = "text" id = "key_class" onkeyup = "keyUpFunction()">
<script>
var demoObj = document.getElementById("key_class");
demoObj.onkeyup = keyUpFunction;
</script>
<script>
var demoObj = document.getElementById("key_class");
demoObj.addEventListener("keyup", keyUpFunction);
</script>
Examples
The JavaScript keyup event operates in conjunction with an HTML element and a corresponding JavaScript function.
Example 1
The alert notification displays the custom functionality defined by the user following the execution of the keyup function.
<!DOCTYPE html>
<html>
<head>
<title> keyup function in javascript </title>
<style>
#datas {
color: green;
}
</style>
</head>
<body>
<h2> JavaScript keyup Method </h2>
<div id = "demoDIV" >
The javascript keyup event works after pressing the key and key in the up position on the specific tag.
</div>
<input type = "text" id = "key_class" placeholder = "write here." onkeyup = "keyUpFunction()">
<p id = "datas"> </p>
<script>
function keyUpFunction() {
alert("JavaScript keyUp function activates successfully!!!");
document.getElementById("datas").innerHTML = "JavaScript keyUp function activates successfully!!!";
}
</script>
</body>
</html>
Output
The alert dialog displays the result of the keydown event.
Example 2
The JavaScript keyup event utilizes an HTML element in conjunction with a JavaScript function. Following the execution of the keyup event, we can modify the style attributes of the container.
<!DOCTYPE html>
<html>
<head>
<title> keyup function in javascript </title>
<style>
#datas {
color: green;
}
</style>
</head>
<body>
<h2> JavaScript keyup Method </h2>
<div id = "demoDIV" >
The javascript keyup event works after pressing the key and key in the up position on the specific tag.
<textarea id = "key_class" placeholder = "write message here."> </textarea>
<p id = "datas"> </p>
</div>
<script>
var demoObj = document.getElementById("key_class");
demoObj.onkeyup = keyUpFunction;
function keyUpFunction() {
console.log("JavaScript keyUp function!!");
document.getElementById("datas").innerHTML = "JavaScript keyUp function activates successfully!!!";
document.getElementById("demoDIV").style.width = "440px";
document.getElementById("demoDIV").style.border = "4px solid red";
document.getElementById("demoDIV").style.color= "Green";
}
</script>
</body>
</html>
Output
The web page shows the output of the keyup event.
Example 3
The addEventListener method is utilized for handling the keyup event in JavaScript. This keyup event can be applied to either individual or multiple checkbox inputs through the use of an input tag.
<!DOCTYPE html>
<html>
<head>
<title> keyup function in javascript </title>
<style>
#datas {
color: green;
}
</style>
</head>
<body>
<h2> JavaScript keyup Method </h2>
<div id = "demoDIV" >
The javascript keyup event works after pressing the key and key in the up position on the specific tag.
</div>
<input type = "checkbox" id = "key_class" placeholder = "write here."> Good
<input type = "checkbox" id = "key_class" placeholder = "write here."> Better
<input type = "checkbox" id = "key_class" placeholder = "write here."> Best
<p id = "datas"> </p>
<script>
var demoObj = document.getElementById("key_class");
demoObj.addEventListener("keyup", keyUpFunction);
function keyUpFunction() {
console.log("JavaScript keyUp function!!");
document.getElementById("datas").innerHTML = "JavaScript keyUp function activates successfully!!!";
document.getElementById("demoDIV").style.width = "440px";
document.getElementById("demoDIV").style.border = "4px dotted navy";
document.getElementById("demoDIV").style.color= "orange";
}
</script>
</body>
</html>
Output
The web page shows the output of the keyup event.
Javascript keypress event
When a key is activated and remains in its initial position on the keyboard, the JavaScript key press event functions within the application. This keyboard event is applicable to input fields on the web page, including forms, search boxes, and various other components.
Syntax
The syntax for the keypress event outlined below illustrates the location of the keyboard key and its usage.
- In Html
- In Javascript
- In addEventListener event
<input type = "text" id = "key_class" onkeypress = "keyPressFunction()">
<script>
demoObj.onkeypress = keyPressFunction;
</script>
<script>
demoObj.addEventListener("keypress", keyPressFunction);
</script>
Examples
The JavaScript keypress event utilizes HTML tags in conjunction with JavaScript functions.
Example 1
The notification message displays the custom functionality implemented after the keypress event is triggered. It is evident that the keypress event operates correctly with the input element, however, it fails to function with the button element. Additionally, even when the input element is set to type submit, the event remains inactive.
<!DOCTYPE html>
<html>
<head>
<title> keypress function in javascript </title>
<style>
#datas {
color: green;
}
</style>
</head>
<body>
<h2> JavaScript keypress Method </h2>
<div id = "demoDIV" >
The javascript keypress event works after pressing the key and key in the press position on the specific tag.
</div>
<input type = "text" id = "key_class" placeholder = "write here." onkeypress = "keyPressFunction()">
<button type = "button" onkeypress = "keyPressFunction2()">
Click here... </button>
<p id = "datas"> </p>
<script>
function keyPressFunction() {
document.getElementById("datas").innerHTML = "JavaScript keyPress function activates successfully!!!";
}
function keyPressFunction2() {
alert("JavaScript keyPress function activates successfully!!!");
document.getElementById("datas").innerHTML = "JavaScript keyPress function activates successfully!!!";
}
</script>
</body>
</html>
Output
The alert dialog displays the result of the keypress event.
Example 2
The JavaScript keypress event relies on HTML elements and associated JavaScript functionalities. After the execution of the keypress event, we can modify the style attributes of the container. The input element designated for text input, along with the texture element, is compatible with the keypress event.
<!DOCTYPE html>
<html>
<head>
<title> keypress function in javascript </title>
<style>
#datas {
color: green;
}
</style>
</head>
<body>
<h2> JavaScript keypress Method </h2>
<div id = "demoDIV" >
The javascript keypress event works after pressing the key and key in the press position on the specific tag. <br>
<textarea id = "key_class" placeholder = "write message here."> </textarea>
<p id = "datas"> </p>
</div>
<script>
var demoObj = document.getElementById("key_class");
demoObj.onkeypress = keyPressFunction;
function keyPressFunction() {
console.log("JavaScript keyPress function!!");
document.getElementById("datas").innerHTML = "JavaScript keyPress function activates successfully!!!";
document.getElementById("demoDIV").style.width = "440px";
document.getElementById("demoDIV").style.border = "4px solid yellow";
document.getElementById("demoDIV").style.color= "Green";
}
</script>
</body>
</html>
Output
The webpage displays the result of the keypress event.
Example 3
The addEventListener method is utilized for handling the keypress event in JavaScript. The keypress event functions effectively on one or more checkbox buttons that utilize an input tag.
<!DOCTYPE html>
<html>
<head>
<title> keypress function in javascript </title>
<style>
#datas {
color: green;
}
</style>
</head>
<body>
<h2> JavaScript keypress Method </h2>
<div id = "demoDIV" >
The javascript keypress event works after pressing the key and key in the press position on the specific tag.
</div>
<input type = "checkbox" id = "key_class" placeholder = "write here."> Good
<input type = "checkbox" id = "key_class" placeholder = "write here."> Better
<input type = "checkbox" id = "key_class" placeholder = "write here."> Best
<p id = "datas"> </p>
<script>
var demoObj = document.getElementById("key_class");
demoObj.addEventListener("keypress", keyPressFunction);
function keyPressFunction() {
console.log("JavaScript keyPress function!!");
document.getElementById("datas").innerHTML = "JavaScript keyPress function activates successfully!!!";
document.getElementById("demoDIV").style.width = "440px";
document.getElementById("demoDIV").style.border = "4px dotted navy";
document.getElementById("demoDIV").style.color= "orange";
}
</script>
</body>
</html>
Output
The web page displays the results generated by the keypress event.
KeyboardEvent flowchart
The following sequence is used to operate KeyboardEvent events on the web page:
- The key-down event is the first event of the keyboard function. If a key down generates a character and it holds down longer, then the event occurrence repeats on the page.
- The keypress event is second fired and repeated as long as the key is depressed on the input tag. It works each time key is pressed on the input tag.
- The keyup event is the last keyboard function. When the key is released from the keyboard, the function operates on the page.
Example
The subsequent example illustrates how to handle keyboard events alongside the flowchart feature. We are able to capture keyboard events along with their respective values and identify which event instigated the value. Furthermore, we can consolidate all functions along with the corresponding output value. In this context, we can utilize either the addEventListener method or the HTML function tag to execute the desired functionality.
<!DOCTYPE html>
<html>
<head>
<title> keypress function in javascript </title>
<style>
#datas {
color: green;
}
</style>
</head>
<body>
<h2> JavaScript keypress Method </h2>
<div id = "demoDIV" >
The javascript key down, keypress and keyup events work after entering, pressing, and releasing keys, respectively, in the javascript using the specific tag. <br>
<input type="text" id="key_class" placeholder="write message here." />
<p id = "datas"> </p>
<p id = "status"> </p>
<p id = "status1"> </p>
<p id = "status2"> </p>
</div>
<script>
var demoObj = document.getElementById("key_class");
demoObj.onkeydown = keyDownFunction;
demoObj.onkeypress = keyPressFunction;
demoObj.onkeyup = keyUpFunction;
function keyDownFunction() {
console.log("JavaScript keyDown function!!");
document.getElementById("datas").innerHTML = "JavaScript keydown function activates successfully!!!";
document.getElementById("status").innerHTML = `<b>keydown: </b> ${event.key} <b>keyCode: </b> ${event.code} <br>`;
}
function keyPressFunction() {
console.log("JavaScript keyPress function!!");
document.getElementById("datas").innerHTML = "JavaScript keyPress function activates successfully!!!";
document.getElementById("status1").innerHTML = `<b>keypress: </b> ${event.key} <b>keyCode: </b> ${event.code} <br>`;
}
function keyUpFunction() {
console.log("JavaScript keyUp function!!");
document.getElementById("datas").innerHTML = "JavaScript keyup function activates successfully!!!";
document.getElementById("status2").innerHTML = `<b>keyup: </b> ${event.key} <b>keyCode: </b> ${event.code} <br>`;
}
</script>
</body>
</html>
Output
The webpage displays the output for the key down, keypress, and keyup events.
A common use of the keyboard event
Computer gaming has emerged as one of the most widely embraced uses of keyboard events in contemporary times. A significant number of web-based games require some form of keyboard interaction. The response of game objects varies based on the specific keyboard event that occurs. Furthermore, this tutorial will demonstrate the implementation of keyboard events within gaming contexts.
Example
The subsequent example illustrates the keyboard event alongside the functionality of a flowchart. In a gaming application, we can capture the keyboard event by utilizing JavaScript functions.
<!DOCTYPE html>
<html>
<head>
<title> keypress function in javascript </title>
<style>
.datas {
background-color: green;
}
</style>
</head>
<body>
<h2> JavaScript keypress Method </h2>
<p>Use the arrow keys to control the square object.</p>
<svg width="200px" height="200px" class="datas">
<rect id="objectval1" x="10" y="10" width="15" height="15" fill="yellow" />
</svg>
<script>
// Declare and assign variables.
let objectval1Size = {
width: 15,
height: 15
};
let position = {
x: 10,
y: 10
};
let moveRate = 10;
let objectval1 = document.getElementById("objectval1");
function updateYPosition(distance) {
position.y = position.y - distance;
// Update the y-axis position at the edge.
if (position.y < 0) {
position.y = 249;
} else if (position.y > 249) {
position.y = 0;
}
}
// Update x-axis position.
function updateXPosition(distance) {
position.x = position.x + distance;
// Update the x-axis position at the edge.
if (position.x < 0) {
position.x = 499;
} else if (position.x > 499) {
position.x = 0;
}
}
function refreshEventPosition() {
let x_val = position.x - (objectval1Size.width/2);
let y_val = position.y - (objectval1Size.height/2);
let transform = "translate(" + x_val + " " + y_val + ")";
objectval1.setAttribute("transform", transform);
}
window.addEventListener("keydown", function(event) {
if (event.defaultPrevented) {
return;
}
if (event.code === "ArrowDown"){
// Handle key "down"
updateYPosition(-moveRate);
} else if (event.code === "ArrowUp"){
// Handle key "up."
updateYPosition(moveRate);
} else if (event.code === "ArrowLeft"){
// Handle key "left"
updateXPosition(-moveRate);
} else if (event.code === "ArrowRight"){
// Handle key "right."
updateXPosition(moveRate);
}
refreshEventPosition();
event.preventDefault();
}, true);
</script>
</body>
</html>
Output
The webpage displays the results of the key down, keypress, and keyup events occurring within the game application.
Different key press
Keyboard events are triggered by key presses involving letters, numbers, and special characters. Additionally, we can capture events for other keys, including alt, control, arrow keys, tab, caps lock, and more.
Example
The example demonstrates how to identify which key has been pressed on the keyboard while also displaying relevant event information. Additionally, we can utilize various keyboard events and JavaScript functions to retrieve further details about the event.
<!DOCTYPE html>
<html>
<head>
<title> keydown function in javascript </title>
<style>
#datas {
color: green;
}
</style>
</head>
<body>
<h2> JavaScript keydown Method </h2>
<h4> The altKey Property </h4>
<p> We can Press a key on the keyboard in the input field to get the respective key is the ALT key or not.</p>
<input type = "text" onkeydown = "keyDownFunction(event)">
<p id = "demos"></p>
<script>
function keyDownFunction(event) {
const var1 = document.getElementById("demos");
if (event.altKey) {
var1.innerHTML = "The ALT key press successfully with keydown event!";
} else {
var1.innerHTML = "The other press (ALT key does not) successfully with keydown event!!";
}
}
</script>
</body>
</html>
Output
The keydown event shows alt keys functionality.
Conclusion
Keyboard events are triggered when a key is engaged for interactive functions by the user. These keys respond to three specific events: key press, key up, and key down, all occurring on the web page.