본문 바로가기
개념/혼자 공부하는 Javascript

chapter 7) Keyboard event

by kiseno 2024. 12. 19.
728x90
반응형
SMALL
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const h1 = document.querySelector('h1');
            const print = (event) => {
                let output ='';
                output += 'alt : ' + event.altKey + '<br>';
                output += 'ctrl : ' + event.ctrlKey + '<br>';
                output += 'shift: ' + event.shiftKey + '<br>';
                output += 'code : ' + (typeof(event.code) !== 'undefined' ? event.code : event.keyCode) + '<br>';
                h1.innerHTML = output;
            };

            document.addEventListener('keydown', print);
            document.addEventListener('keyup', print);
        });
    </script>
</head>
<body>
<h1></h1>
</body>
</html>

### How It Works

- **Event Listening for DOM Content Loaded**: The `DOMContentLoaded` event ensures that the JavaScript code runs only after the HTML document has been completely parsed. This is crucial for accessing DOM elements like `<h1>`.

- **Query Selector for `<h1>` Element**: The `document.querySelector('h1')` method is used to select the first `<h1>` element in the document, which will be used to display the output of keyboard events.

- **Print Function**: The `print` function is an event handler that constructs a string containing the status of the `Alt`, `Ctrl`, and `Shift` keys (`true` if any of these keys were pressed during the event, `false` otherwise), as well as the `code` (or `keyCode` for older browsers) of the key pressed or released. This string is then set as the `innerHTML` of the `<h1>` element, updating its content to reflect the properties of the last key event.

  - `event.altKey`, `event.ctrlKey`, and `event.shiftKey` indicate whether the Alt, Ctrl, or Shift keys were pressed.
  
  - `event.code` provides a string representing the physical key on the keyboard (like `'KeyA'` for the "A" key), while `event.keyCode` is a deprecated property that gives the numeric code of the key. The ternary operator checks if `event.code` is available and uses it; otherwise, it falls back to `event.keyCode`.

- **Event Listeners for Key Events**: Event listeners are added to the entire document for both `keydown` and `keyup` events, calling the `print` function when these events occur.

### Behavior

When you press or release a key on your keyboard while focusing anywhere on the page:

- The status of the `Alt`, `Ctrl`, and `Shift` keys at the time of the event is displayed in the `<h1>` element.
- The `code` (or `keyCode`) of the key that was interacted with is shown.
- This information is updated with each key press or release, showing the most recent event's details.

### Practical Use

This setup can be particularly useful for debugging keyboard interactions, understanding how different keys and key combinations are recognized by the browser, and developing complex keyboard shortcuts or controls for web applications. It provides clear, real-time feedback on keyboard events, which can aid in developing accessible and interactive web content.

728x90
반응형
LIST

'개념 > 혼자 공부하는 Javascript' 카테고리의 다른 글

chapter 7) DomContentLoaded event  (0) 2024.12.22
chapter 7) handle to javascript code in HTML  (1) 2024.12.21
chapter 7) localStroage  (0) 2024.12.18
chapter 7) Manipulating  (1) 2024.12.17
chapter 7) select tag  (0) 2024.12.16