Home > CMS Tutorial > WordPress > body text

JavaScript: capture keyboard events and react to them

PHPz
Release: 2023-09-04 20:57:02
Original
797 people have browsed it

JavaScript: capture keyboard events and react to them

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);
Copy after login

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);
Copy after login

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>
Copy after login

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);
Copy after login

在上面的示例中,当您按下任意键时,将首先触发 keydown 事件,然后触发 keyup 事件。例如,如果您按 a 键,您应该在控制台上看到以下输出。请务必注意事件的触发顺序。

keydown event, keyValue: a
keydown event, codeValue: KeyA
keyup event, keyValue: a
keyup event, codeValue: KeyA
Copy after login

让我们看一下以下示例,它演示了如何在项目中使用 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>
Copy after login

在上面的示例中,我们在输入文本框上定义了 onkeyup 事件。因此,当用户在文本框中输入任何文本时,它都会调用 getSearchResults 函数。在 getSearchResults 函数中,我们将进行 AJAX 调用来获取搜索关键字的搜索结果。这也称为实时搜索,因为它会立即显示搜索结果,而无需刷新整个页面。

重要的 KeyboardEvent 对象属性

在最后一节中,我将总结 KeyboardEvent 对象的重要属性。事实上,我们已经在到目前为止讨论的示例中看到了一些常用的属性,例如 keycode。我们还将在本节中讨论一些其他重要属性。

  • <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 键是键盘上位于 CtrlAlt 键之间的键。
  • <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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!