JavaScript: Mastering Keyboard Event Handling
Website developers want readers to interact with their website in some way. Visitors can scroll up and down the page, write in input fields, click a link to access another page, or press key combinations to trigger specific actions. As a developer, you should be able to capture all these events and provide the required functionality to the user.
In this tutorial, our focus will be on handling keyboard events in JavaScript. We'll learn about the different types of keyboard events, handling special key events, and getting information about keys that are pressed or released.
Keyboard event type
Keyboard events are divided into three types. These are called keydown
, keypress
, and keyup
.
As long as a key is pressed, the keydown
event will be triggered. All keys will be triggered. It doesn't matter whether they generate character value. For example, pressing the A or Alt key on the keyboard will trigger the keydown
event.
keypress
event is deprecated. It only fires when the key that produces the character value is pressed. For example, pressing the A key will trigger this event, but pressing the Alt key will not. You should consider using the keydown
event instead.
When the key pressed by the user is released, the keyup
event will be triggered.
Suppose the user presses any key on the keyboard continuously. In this case, the keydown
event will be triggered repeatedly. Once the user releases the key, the keyup
event is triggered.
Listen to keyboard events
At this point, I want to mention something fairly obvious. A keyboard is an input device used to get some input from the user. We take action based on that input. However, there are other ways for users to send input.
If you want to track any input fields that the user fills out in a form, it makes more sense to use other events on said inputs (such as change
).
Additionally, keyboard events are generated only for elements that can receive focus. This includes <input>
elements, <textarea></textarea>
elements, <summary></summary>
elements, and elements with contentEditable
or tabindex
Other elements of attributes.
For example, you cannot listen to keyboard events on a paragraph element unless you set the tabindex
or contentEditable
properties. However, it will eventually bubble up in the DOM tree, so you can still attach a keydown
or keyup
event listener to the document.
This is an example:
document.addEventListener("keydown", keyIsDown); function keyIsDown(event) { // Do whatever you want! }
You can also provide the callback as an arrow function:
document.addEventListener("keydown", (event) => { // Do whatever you want! });
Get information from keyboard events
In the basic code snippet of the previous section, we defined a callback function. This function accepts an event
object as its argument. This event
object contains all the information you might need to access related to the keydown
or keyup
event.
Here are some useful properties you should know about:
-
key
: This property returns a string representing the character value of the key pressed. -
code
: This property returns a string representing the code of the physical key pressed. -
repeat
: If a key is pressed for a long time, this property will return a Boolean valuetrue
, causing thekeydown
event to be triggered multiple times. -
altKey
: If the user presses the Alt key (on Windows) or the Option key (on macOS) whenWhen the keydown
event is triggered. -
ctrlKey
: If the user presses theControl
key when the keydown event fires, this property returns a Boolean valuetrue
. -
metaKey
: If the user presses theMeta
key when the keydown event fires, this property returns a Boolean valuetrue
. -
shiftKey
: If the user presses theShift
key when the keydown event fires, this property returns a Boolean valuetrue
.
You'll notice that I've included the "when the keydown
event is fired" part in all the last four property descriptions. This means that if a key such as A or 3 is pressed while performing any of the above actions, the value of these properties will be true
for keydown
event. The key is also pressed.
After focusing on the following CodePen demo, try pressing individual keys or key combinations to see the values of different properties change.
如果您按键盘顶部的 3 键而不按 Shift 键,则 key
属性的值将变为 3 > 并且 code
属性的值变为 Digit3。但是,按下 Shift 后,key
属性的值将变为 #,而 code
属性仍为 Digit3。
您可以尝试使用其他组合键进行相同的操作,您会注意到 key
属性的值会根据您按下的键而变化。但是,code
属性的值保持不变。
键盘上的某些键通常是重复的。例如,有两个 Shift 键。按左键会将 code
的值设置为 ShiftLeft
。按右边会将 code
的值设置为 ShiftRight
。同样,有两组数字键。字母上方的代码将为您提供 Digit<Number>
代码,而数字键盘上的代码将为您提供 Numpad<Number>
代码。
这意味着,如果您的代码依赖于检测特定键,则务必确保您使用 code
属性来检查按下了哪个键。
我想提的另一件重要的事情是,并不是每个人都使用 QWERTY 键盘,而且他们的键盘甚至可能不是英文的。在这种情况下,使用 key
属性来检查按下了哪个键很容易出错。
响应键盘事件
现在我们知道了如何监听键盘事件并从中提取信息,我们可以编写一些代码来对某些特定键的 keydown
和 keyup
事件做出反应。考虑以下代码片段:
const circle = document.querySelector(".circle"); document.addEventListener("keydown", (event) => { if (event.code == "KeyR" && event.repeat != true) { let rVal = Math.floor(200 + Math.random() * 200); circle.setAttribute("style", `width: ${rVal}px; height: ${rVal}px;`); } if (event.key == "B" && event.shiftKey == true) { let rVal = Math.floor(10 + Math.random() * 40); circle.setAttribute("style", `border: ${rVal}px solid orangered;`); } if (event.code == "ArrowUp" && event.repeat != true) { circle.classList.add("animate__animated", "animate__bounce"); } }); document.addEventListener("keyup", (event) => { if (event.code == "ArrowUp") { setTimeout(() => { circle.classList.remove("animate__animated", "animate__bounce"); }, 4000); } });
我们为 keydown
事件创建了一个侦听器,并为 keyup
事件创建了另一个侦听器。这两个事件都附加到 document
。
在 keydown
内,我们检查三个不同的密钥。我使用了 R 键的 event.code
属性来向您展示您可以单独按 R 键或与任何修饰键组合使用,并且它仍会将圆的半径更改为随机值。另一方面,我们使用 event.key
属性来检查其值是否为 B。仅当您同时按 Shift 和 B 时,此块中的代码才会执行,因为这种组合会导致 event.key
属性成为大写“B”。
在 keyup
内,我们检查 ArrowUp
键上的 keyup
事件。一旦钥匙被解除,我们会在四秒的延迟后删除之前附加的类。
以下 CodePen 演示展示了这一切的实际效果:
您应该尝试在上述代码中添加自己的逻辑,以便当用户按下A、S、W键时圆圈会移动> 和D。
最终想法
在本教程中,我们学习了 JavaScript 中键盘事件的基础知识。按下并释放键盘上的按键将分别触发 keydown
和 keyup
事件。与这些事件关联的 event
对象包含您确定按下了哪个键并采取适当操作所需的所有信息。
请记住,键盘只是众多可能的输入设备之一。因此,使用键盘检测任何输入可能并不总是能达到预期效果。在这种情况下,您应该考虑使用与输入相关的事件。
The above is the detailed content of JavaScript: Mastering Keyboard Event Handling. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Blogs are the ideal platform for people to express their opinions, opinions and opinions online. Many newbies are eager to build their own website but are hesitant to worry about technical barriers or cost issues. However, as the platform continues to evolve to meet the capabilities and needs of beginners, it is now starting to become easier than ever. This article will guide you step by step how to build a WordPress blog, from theme selection to using plugins to improve security and performance, helping you create your own website easily. Choose a blog topic and direction Before purchasing a domain name or registering a host, it is best to identify the topics you plan to cover. Personal websites can revolve around travel, cooking, product reviews, music or any hobby that sparks your interests. Focusing on areas you are truly interested in can encourage continuous writing

There are four ways to adjust the WordPress article list: use theme options, use plugins (such as Post Types Order, WP Post List, Boxy Stuff), use code (add settings in the functions.php file), or modify the WordPress database directly.

Recently, we showed you how to create a personalized experience for users by allowing users to save their favorite posts in a personalized library. You can take personalized results to another level by using their names in some places (i.e., welcome screens). Fortunately, WordPress makes it very easy to get information about logged in users. In this article, we will show you how to retrieve information related to the currently logged in user. We will use the get_currentuserinfo(); function. This can be used anywhere in the theme (header, footer, sidebar, page template, etc.). In order for it to work, the user must be logged in. So we need to use

Do you want to know how to display child categories on the parent category archive page? When you customize a classification archive page, you may need to do this to make it more useful to your visitors. In this article, we will show you how to easily display child categories on the parent category archive page. Why do subcategories appear on parent category archive page? By displaying all child categories on the parent category archive page, you can make them less generic and more useful to visitors. For example, if you run a WordPress blog about books and have a taxonomy called "Theme", you can add sub-taxonomy such as "novel", "non-fiction" so that your readers can

In the past, we have shared how to use the PostExpirator plugin to expire posts in WordPress. Well, when creating the activity list website, we found this plugin to be very useful. We can easily delete expired activity lists. Secondly, thanks to this plugin, it is also very easy to sort posts by post expiration date. In this article, we will show you how to sort posts by post expiration date in WordPress. Updated code to reflect changes in the plugin to change the custom field name. Thanks Tajim for letting us know in the comments. In our specific project, we use events as custom post types. Now

Are you looking for ways to automate your WordPress website and social media accounts? With automation, you will be able to automatically share your WordPress blog posts or updates on Facebook, Twitter, LinkedIn, Instagram and more. In this article, we will show you how to easily automate WordPress and social media using IFTTT, Zapier, and Uncanny Automator. Why Automate WordPress and Social Media? Automate your WordPre

One of our users asked other websites how to display the number of queries and page loading time in the footer. You often see this in the footer of your website, and it may display something like: "64 queries in 1.248 seconds". In this article, we will show you how to display the number of queries and page loading time in WordPress. Just paste the following code anywhere you like in the theme file (e.g. footer.php). queriesin

To build a website using WordPress hosting, you need to: select a reliable hosting provider. Buy a domain name. Set up a WordPress hosting account. Select a topic. Add pages and articles. Install the plug-in. Customize your website. Publish your website.
