How to Create Keyboard Shortcuts in JavaScript ?
Last Updated :
10 Oct, 2023
This article will demonstrate how to create keyboard shortcuts in JavaScript. We can manually set user-defined functions for different shortcut keys.
Keyboard shortcuts allow users to perform actions quickly by pressing a combination of keys, such as Ctrl + S for saving, Ctrl + C for copying, or custom shortcuts tailored to your web application's needs. To implement these shortcuts, you need to define custom/user-defined functions that are triggered when the specified key combinations are pressed.
Syntax
Creating a basic keyboard shortcut in JavaScript typically involves the following syntax:
function handleShortcut(event) {
if (event.key === "YOUR_KEY") {
event.preventDefault();
// Your action to perform when the key is pressed
}
}
document.addEventListener("keydown", handleShortcut);
Here
- handleShortcut: This is the function that handles the keyboard shortcut.
- event.key: Represents the key that triggers the shortcut.
- event.preventDefault(): Prevents the default behavior associated with the key.
- document.addEventListener("keydown", handleShortcut): Listens for a "keydown" event on the document and calls the handleShortcut function when the specified key is pressed.
Approach for creating shortcuts in JavaScript
- Define Custom Functions: Create functions for each shortcut key action you want to implement. These functions contain the code to execute when the shortcut key is pressed.
- Listen for Keyboard Events: Use JavaScript's event listeners to detect keyboard events, such as "keydown" or "keyup." Assign these event listeners to specific elements, such as the document or a specific input field.
- Trigger Custom Functions: Within the event listener function, check if the pressed key combination matches the desired shortcut. If it matches, call the corresponding custom function to execute the desired action.
Example 1: Showing an Alert on "Ctrl + A"
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Custom Function Example
</title>
<style>
h1 {
margin-left: 40%;
color: green;
}
p {
margin-left: 40%;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>
<p>Press A for Showing an Alert </p>
<script>
function showAlert() {
alert("A was pressed!");
}
document
.addEventListener("keydown",
function (event) {
if (event.key === "a") {
event.preventDefault();
showAlert();
}
});
</script>
</body>
</html>
Output:

Example 2: Toggling Visibility on "Spacebar"
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Custom Function Example
</title>
<style>
#element {
display: none;
}
h1 {
margin-left: 40%;
color: green;
}
p {
margin-left: 40%;
}
</style>
</head>
<body>
<p>Press Spacebar for showing
toggled element </p>
<div id="element">
<h1>GeeksforGeeks</h1>
</div>
<script>
function toggleVisibility() {
const element = document
.getElementById("element");
element.style.display = element.style
.display === "none" ? "block" : "none";
}
document
.addEventListener("keydown",
function (event) {
if (event.key === " ") {
// Spacebar
event.preventDefault();
toggleVisibility();
}
});
</script>
</body>
</html>
Output:

Example 3: Changing Background Color on "Y"
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Custom Function Example
</title>
</head>
<body>
<style>
h1 {
margin-left: 40%;
color: green;
}
p {
margin-left: 40%;
}
body {
background-color: white;
}
</style>
<h1>GeeksforGeeks</h1>
<p>Press Y for color change white to
yellow </p>
<script>
function changeBackgroundColor() {
document.body.style.backgroundColor = "yellow";
}
document.addEventListener("keydown",
function (event) {
if (event.key === "y") {
event.preventDefault();
changeBackgroundColor();
}
});
</script>
</body>
</html>
Output:

Example 4: Opening a Link in a New Tab on "O"
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Custom Function Example
</title>
<style>
h1 {
margin-left: 40%;
color: green;
text-decoration: none;
outline: none;
}
p {
margin-left: 40%;
text-decoration: none;
outline: none;
color: black;
}
a {
text-decoration: none;
}
</style>
</head>
<body>
<a href="https://geeksforgeeks.org"
id="myLink">
<h1>GeeksforGeeks</h1>
<p>Press O for Redirect on
newlink (website) </p>
</a>
<script>
function openLinkInNewTab() {
window.open(
document.getElementById(
"myLink").href, "_blank"
);
}
document
.addEventListener("keydown",
function (event) {
if (event.key === "o") {
event.preventDefault();
openLinkInNewTab();
}
});
</script>
</body>
</html>
Output:

Conclusion
In conclusion, custom/user-defined functions for handling shortcut keys in web applications offer a powerful means to enhance user interactivity and productivity. These functions empower users to navigate and interact with the application more efficiently, reducing the learning curve and streamlining workflows. Additionally, the adaptability of custom shortcuts to the application's specific requirements and the potential to boost user productivity make them a valuable feature for improving the overall user experience. By implementing these functions, web applications can provide a more user-friendly and efficient environment, ultimately leading to increased user satisfaction and success.
Similar Reads
How to Create a Link in JavaScript ? In JavaScript, a link typically refers to creating HTML hyperlinks (<a> tags) dynamically using JavaScript. You can link using a document.createElement('a'), setting attributes like href and textContent, and then appending it to the document with appendChild().Here are some common approaches t
4 min read
Keyboard Shortcuts in ElectronJS ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.U
6 min read
How to Disable Ctrl+V (Paste) in JavaScript? What is Ctrl + V ?The ctrl+V is a keyboard shortcut used to paste anything from anywhere. It can be disabled for a particular task or page. Let's see how to disable cut, copy, paste, and right-click. To disable the ctrl+V (paste) keyboard shortcut in JavaScript, you would typically capture the keydo
3 min read
How to Detect Keypress using JavaScript ? In this article, keyboard detection is performed using HTML and CSS. HTML stands for "Hypertext Markup Language". HTML language helps the developer to create and design web page elements like links, sections, paragraphs, headings, and blockquotes for web applications. CSS stands for "Cascading Style
2 min read
How to disable arrow key in textarea using JavaScript ? Given an HTML element containing the <textarea> element and the task is to disable scrolling through arrow keys with the help of JavaScript. Approach 1: Add an event listener onkeydown on the window.If the event happens then check if the keys are arrow or not.If arrow key is pressed then preve
3 min read
How to Simulate a Click in JavaScript? Simulating a click in JavaScript means triggering a click event on an HTML element using code, rather than requiring manual user interaction. This technique is useful for automating actions like clicking buttons, links, or other interactive elements, enhancing web functionality, and triggering hidde
3 min read
How to find out which Character Key is Pressed using JavaScript? To find which key is pressed in JavaScript, use event listeners like keydown, keypress, or keyup. By accessing properties such as event.key or event.code, it becomes easy to identify the specific key pressed. This approach is useful for handling user input and triggering actions based on key events.
2 min read
How to Handle Mouse and Keyboard Input in WebGL? WebGL in web development is a JavaScript API that allows for the rendering of interactive 2D and 3D graphics within a web browser without the need for plugins. Handling mouse and keyboard input in WebGL involves capturing these inputs through event listeners and using them to manipulate the graphics
4 min read
How to Disable Ctrl + C in JavaScript ? Disabling Ctrl+C in JavaScript involves intercepting the keyboard event and preventing the default action associated with the combination. There are several approaches to disable Ctrl+C in JavaScript which are as follows: Table of Content Using Event ListenersModifying the clipboard eventUsing Event
2 min read
How to create an object from the given key-value pairs using JavaScript ? In this article, we will learn to create an object from the given key-value pairs using JavaScript.Key-value pair: Unique identifier (key) associated with its corresponding value; fundamental for data organization and retrieval in programming. here we have some common approaches.We will explore the
5 min read