In this article, we will discuss how to catch and respond to different keyboard events in JavaScript. I'll show you a few real-world examples to make it easy to understand.
JavaScript is one of the core technologies of the Internet. It is used by most websites and supported by all modern web browsers without the need for plugins. In this series, we will discuss different tips and tricks that will help you with your daily JavaScript development.
As a JavaScript developer, sometimes you need to implement functionality that requires you to handle keyboard events and perform actions based on them. Fortunately, JavaScript provides a built-in KeyboardEvent
object that allows you to handle different types of keyboard events.
Keyboard events in JavaScript
In JavaScript, the KeyboardEvent
object provides three events: key down, key down, and key up.
When you press any key on the keyboard, a series of events will occur in the following order.
- Press key
- button
- button
When any key on the keyboard is pressed, a key event is triggered. And if a key is pressed for a long time, the key press event will be triggered repeatedly.
Key events are mainly triggered when any printable character is pressed, and are triggered after key events. In fact, the key event is used to relay the characters produced by the key event. In most cases, non-character keys do not raise key events. Although some browsers support this event, relying on this event is not recommended as it will be removed from the web standard.
Key events have been deprecated and will be phased out in modern browsers.Finally, the key event is fired when the key is released. Basically, the combination of keypress and keydown events gives you a code that indicates which key was pressed.
Each keyboard event provides two important properties: key
and code
. The key
attribute is filled with the pressed character, while the code
attribute is filled with the character's physical key position. For example, if you press the a
character key, the key property will be populated with a
, and the code
property will be populated with the KeyA
constant. However, the keycode pressed is not necessarily the same as the character! If the user has an alternate keyboard layout set up, such as Dvorak, pressing the same key code will produce different characters.
The above is a brief overview of keyboard events in JavaScript. Starting in the next section, we will discuss these events along with real-world examples to understand how they work.
keydown
Event
In this section, we will learn how the keydown
event works in JavaScript. When any key on the keyboard is pressed, the keydown
event is triggered.
Let’s take a quick look at the following examples.
document.addEventListener('keydown', (event) => { var keyValue = event.key; var codeValue = event.code; console.log("keyValue: " + keyValue); console.log("codeValue: " + codeValue); }, false);
As you can see, we created a listener to listen for the keydown
event. Whenever any key is pressed, our listener will be called and the value and code of that key will be logged to the console. Go ahead and run it and see how it works.
Let's take a look at the following example that demonstrates how to detect whether the user pressed ctrl a or ctrl A.
document.addEventListener('keydown', (event) => { if (event.ctrlKey) { if (event.keyCode == 65 || event.keyCode == 97) { console.log("You have just pressed Ctrl + a/A!"); } } }, false);
First, ctrlKey
is a special property of the KeyboardEvent
object that tells you whether Ctrl was pressed when the
keydown event was triggered key. Therefore, if ctrlKey
is true, it means that the Ctrl key was pressed.
Next, we check the keyCode
value of the pressed character, if it is 65
or 97
, it means a Or A pressed together with the Ctrl key. The KeyboardEvent
object's keyCode
property returns the Unicode character code of the pressed key. Likewise, you can also use the <strong>shiftKey</strong> property of the KeyboardEvent object, which tells you whether the Shift key was pressed during the keypress event. trigger.
Finally, let's look at the following example that demonstrates how to allow only letters in an input field of an HTML form.
<script> function allowOnlyAlphabets(event) { var charCode = event.keyCode; if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123)) return true; else return false; } </script> <html> <body> <div> <input type="text" onkeydown="return allowOnlyAlphabets(event);"> </div> </body> </html>
In the above example, we defined the keydown
event on the input text box. So when the user enters any text in the textbox, it calls the allowOnlyAlphabets
function. In the allowOnlyAlphabets
function, we validate the value of the event object's keyCode
property against the valid Unicode range of the alphabet. Therefore, the allowOnlyAlphabets
function will return true
if the user presses a valid alphabet character, and false
otherwise. The end result is that the user will not be able to enter any characters other than letters.
keyup
事件
在本节中,我们将了解 keyup
事件如何工作。事实上,它的工作原理与 keydown
事件非常相似,唯一的区别是它是在释放按键时触发,而不是在按下按键时触发。
让我们看一下下面的例子。
document.addEventListener('keydown', (event) => { var keyValue = event.key; var codeValue = event.code; console.log("keydown event, keyValue: " + keyValue); console.log("keydown event, codeValue: " + codeValue); }, false); document.addEventListener('keyup', (event) => { var keyValue = event.key; var codeValue = event.code; console.log("keyup event, keyValue: " + keyValue); console.log("keyup event, codeValue: " + codeValue); }, false);
在上面的示例中,当您按下任意键时,将首先触发 keydown
事件,然后触发 keyup
事件。例如,如果您按 a 键,您应该在控制台上看到以下输出。请务必注意事件的触发顺序。
keydown event, keyValue: a keydown event, codeValue: KeyA keyup event, keyValue: a keyup event, codeValue: KeyA
让我们看一下以下示例,它演示了如何在项目中使用 keyup
事件。
<script> function getSearchResults(event, element) { if (element.value.length > 6) { var searchKeyword = element.value; // make an AJAX call to fetch search results for "searchKeyword" } } </script> <html> <body> <div> <input type="text" onkeyup="return getSearchResults(event, this);"> </div> </body> </html>
在上面的示例中,我们在输入文本框上定义了 onkeyup
事件。因此,当用户在文本框中输入任何文本时,它都会调用 getSearchResults
函数。在 getSearchResults
函数中,我们将进行 AJAX 调用来获取搜索关键字的搜索结果。这也称为实时搜索,因为它会立即显示搜索结果,而无需刷新整个页面。
重要的 KeyboardEvent
对象属性
在最后一节中,我将总结 KeyboardEvent
对象的重要属性。事实上,我们已经在到目前为止讨论的示例中看到了一些常用的属性,例如 key
和 code
。我们还将在本节中讨论一些其他重要属性。
-
<strong>key</strong>
:返回按下的字符。例如,如果按下a字符,则会返回a
。 -
<strong>code</strong>
:返回字符的物理键码。例如,如果按下a字符,则会返回KeyA
。 -
<strong>keyCode</strong>
:返回按下的按键的Unicode字符代码。 -
<strong>ctrlKey</strong>
:告诉您触发按键事件时是否按下Ctrl键。 -
<strong>altKey</strong>
:告诉您触发按键事件时是否按下了Alt键。 -
<strong>shiftKey</strong>
:告诉您触发按键事件时是否按下Shift键。 -
<strong>metaKey</strong>
:告诉你触发按键事件时是否按下了Meta键。在大多数情况下,Meta 键是键盘上位于 Ctrl 和 Alt 键之间的键。 -
<strong>位置</strong>
:返回键盘或设备上按键的位置。
如您所见,keyboardEvent
对象提供了各种属性,允许您检测不同的按键。在大多数情况下,您将使用 keydown
事件来检测按下的按键并执行相应的操作。正如我们之前讨论的,您不应该使用 keypress
事件,因为它迟早会被弃用。
结论
今天,我们讨论了如何在 JavaScript 中使用键盘事件以及几个实际示例。
The above is the detailed content of JavaScript: capture keyboard events and react to them. For more information, please follow other related articles on the PHP Chinese website!

Yes, WordPress is very suitable for e-commerce. 1) With the WooCommerce plugin, WordPress can quickly become a fully functional online store. 2) Pay attention to performance optimization and security, and regular updates and use of caches and security plug-ins are the key. 3) WordPress provides a wealth of customization options to improve user experience and significantly optimize SEO.

Do you want to connect your website to Yandex Webmaster Tools? Webmaster tools such as Google Search Console, Bing and Yandex can help you optimize your website, monitor traffic, manage robots.txt, check for website errors, and more. In this article, we will share how to add your WordPress website to the Yandex Webmaster Tool to monitor your search engine traffic. What is Yandex? Yandex is a popular search engine based in Russia, similar to Google and Bing. You can excel in Yandex

Do you need to fix HTTP image upload errors in WordPress? This error can be particularly frustrating when you create content in WordPress. This usually happens when you upload images or other files to your CMS using the built-in WordPress media library. In this article, we will show you how to easily fix HTTP image upload errors in WordPress. What is the reason for HTTP errors during WordPress media uploading? When you try to upload files to Wo using WordPress media uploader

Recently, one of our readers reported that the Add Media button on their WordPress site suddenly stopped working. This classic editor problem does not show any errors or warnings, which makes the user unaware why their "Add Media" button does not work. In this article, we will show you how to easily fix the Add Media button in WordPress that doesn't work. What causes WordPress "Add Media" button to stop working? If you are still using the old classic WordPress editor, the Add Media button allows you to insert images, videos, and more into your blog post.

Do you want to know how to use cookies on your WordPress website? Cookies are useful tools for storing temporary information in users’ browsers. You can use this information to enhance the user experience through personalization and behavioral targeting. In this ultimate guide, we will show you how to set, get, and delete WordPresscookies like a professional. Note: This is an advanced tutorial. It requires you to be proficient in HTML, CSS, WordPress websites and PHP. What are cookies? Cookies are created and stored when users visit websites.

Do you see the "429 too many requests" error on your WordPress website? This error message means that the user is sending too many HTTP requests to the server of your website. This error can be very frustrating because it is difficult to find out what causes the error. In this article, we will show you how to easily fix the "WordPress429TooManyRequests" error. What causes too many requests for WordPress429? The most common cause of the "429TooManyRequests" error is that the user, bot, or script attempts to go to the website

WordPresscanhandlelargewebsiteswithcarefulplanningandoptimization.1)Usecachingtoreduceserverload.2)Optimizeyourdatabaseregularly.3)ImplementaCDNtodistributecontent.4)Vetpluginsandthemestoavoidconflicts.5)ConsidermanagedWordPresshostingforenhancedperf

WordPress is very customized, providing a wide range of flexibility and customizability. 1) Through the theme and plug-in ecosystem, 2) use RESTAPI for front-end development, 3) In-depth code level modifications, users can achieve a highly personalized experience. However, customization requires mastering technologies such as PHP, JavaScript, CSS, etc., and pay attention to performance optimization and plug-in selection to avoid potential problems.


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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
