JavaScript onkeyup Event: Key Released

The onkeyup event in JavaScript is a fundamental tool for capturing user interactions with the keyboard. Unlike the onkeydown event, which fires when a key is initially pressed, onkeyup is triggered only after the key has been released. This provides developers with a clear distinction between key press and key release actions, enabling more precise control over keyboard-related functionality. This article will delve into the intricacies of the onkeyup event, covering its syntax, attributes, and practical examples.

Understanding the onkeyup Event

The onkeyup event is part of the Document Object Model (DOM) event system. It occurs when a keyboard key that was previously pressed is released. This event is commonly used in scenarios where an action should occur only after a user has completed a keystroke, such as validating input, submitting forms, or triggering animations.

Syntax of onkeyup

The onkeyup event can be attached to HTML elements in two primary ways:

  1. HTML Attribute: Directly within an HTML element:

    <element onkeyup="script"></element>
    

    Here, element is any HTML element that can receive keyboard events, such as <input>, <textarea>, or even the entire <body>. The script is the JavaScript code to be executed when the event occurs.

  2. JavaScript Property: Assigning an event handler via JavaScript:

    element.onkeyup = function() {
      // JavaScript code to execute
    };
    

    This approach provides more flexibility and better separation of concerns, keeping HTML clean and logic in JavaScript.

Key Attributes of the onkeyup Event

When the onkeyup event is triggered, it generates an event object that contains several useful properties. Here are the most important ones:

Attribute Type Description
`type` String Returns the type of the event, which is always “keyup”.
`target` Element Returns the element that triggered the event.
`key` String Returns the value of the key that was released (e.g., “Enter”, “a”, “Shift”).
`code` String Returns the physical key code (e.g., “Enter”, “KeyA”, “ShiftLeft”).
`shiftKey` Boolean Returns `true` if the Shift key was pressed during the key release. Otherwise, `false`.
`ctrlKey` Boolean Returns `true` if the Ctrl key was pressed during the key release. Otherwise, `false`.
`altKey` Boolean Returns `true` if the Alt key was pressed during the key release. Otherwise, `false`.
`metaKey` Boolean Returns `true` if the Meta key (Command key on macOS, Windows key on Windows) was pressed during the key release. Otherwise, `false`.
`timeStamp` Number Returns the number of milliseconds between the time the document was loaded and the time the event was triggered.
`preventDefault()` Function Prevents the default action of the event, if any.
`stopPropagation()` Function Prevents the event from propagating up the DOM tree.

These properties enable a great deal of control and customization in event handling, allowing you to precisely identify the released key and the state of modifier keys.

Basic Examples of onkeyup

Let’s explore the onkeyup event with some practical examples.

Displaying Released Key

This example demonstrates how to capture and display the value of the key released by the user:

<input type="text" id="keyInput" placeholder="Type something...">
<p>You released: <span id="keyDisplay"></span></p>

<script>
  const keyInput = document.getElementById('keyInput');
  const keyDisplay = document.getElementById('keyDisplay');

  keyInput.onkeyup = function(event) {
    keyDisplay.textContent = event.key;
  };
</script>

In this example, when a key is released within the text input, the event.key property is captured and displayed in the <span> element.

Tracking Input Length

This example illustrates how to track the length of the input as keys are released:

  <textarea id="textInput" placeholder="Enter text here"></textarea>
  <p>Character count: <span id="charCount">0</span></p>

<script>
  const textInput = document.getElementById('textInput');
  const charCount = document.getElementById('charCount');

  textInput.onkeyup = function() {
    charCount.textContent = textInput.value.length;
  };
</script>

Here, the character count is updated each time a key is released inside the textarea.

Clearing Input Field

This example demonstrates using onkeyup to clear the input field when a specific key, like Escape is released.

<input type="text" id="clearInput" placeholder="Type and press ESC to clear">

<script>
  const clearInput = document.getElementById('clearInput');

  clearInput.onkeyup = function(event) {
    if (event.key === 'Escape') {
      clearInput.value = '';
    }
  };
</script>

In this scenario, when the Escape key is released, the text input field is cleared.

Advanced Usage of onkeyup

Let’s explore some more advanced applications of the onkeyup event.

Form Validation

The onkeyup event is commonly used in real-time form validation. Here’s a simple example:

 <input type="email" id="emailInput" placeholder="Enter your email">
  <p id="emailValidation"></p>

<script>
  const emailInput = document.getElementById('emailInput');
  const emailValidation = document.getElementById('emailValidation');

  emailInput.onkeyup = function() {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (emailRegex.test(emailInput.value)) {
      emailValidation.textContent = 'Valid email';
      emailValidation.style.color = 'green';
    } else {
      emailValidation.textContent = 'Invalid email';
      emailValidation.style.color = 'red';
    }
  };
</script>

In this case, the email input is validated in real-time as the user releases keys. The validation message is displayed accordingly.

Interactive Canvas Drawing

The onkeyup event can be integrated with the HTML Canvas API for interactive experiences.

<canvas
  id="interactiveCanvas"
  width="300"
  height="200"
  style="border: 1px solid black;"
></canvas>

<script>
  const interactiveCanvas = document.getElementById("interactiveCanvas");
  const ctx_interactive = interactiveCanvas.getContext("2d");
  let x = 50;
  let y = 50;

  function drawCircle(x_circle, y_circle) {
    ctx_interactive.clearRect(0, 0, interactiveCanvas.width, interactiveCanvas.height);
    ctx_interactive.beginPath();
    ctx_interactive.arc(x_circle, y_circle, 20, 0, 2 * Math.PI);
    ctx_interactive.fillStyle = "blue";
    ctx_interactive.fill();
  }

  drawCircle(x, y);
  document.addEventListener("keyup", function (event) {
      if(event.key === "ArrowUp"){
        y -= 10;
      }
      else if(event.key === "ArrowDown"){
        y+= 10;
      }
       else if(event.key === "ArrowLeft"){
        x-= 10;
      }
      else if(event.key === "ArrowRight"){
        x += 10;
      }
       drawCircle(x, y);
  });
</script>

In this setup, the circle moves on the canvas as the arrow keys are released, creating an interactive visual effect.

Key Differences: onkeydown, onkeypress, and onkeyup

It’s crucial to distinguish the onkeyup event from its counterparts: onkeydown and onkeypress.

  • onkeydown: Fires when a key is initially pressed down. Useful for detecting the start of a keystroke.
  • onkeypress: Fires when a key that produces a character is pressed down. It is deprecated for some keys like arrow keys.
  • onkeyup: Fires when a key is released. Suitable for actions that should occur after a keystroke is completed.
Key Events Timeline:

Press Key Release Key

keydown

keypress

keyup

The onkeypress event is now deprecated for most keys (like arrow keys), so in most practical cases onkeyup and onkeydown are the main events to consider.

Browser Support

The onkeyup event is widely supported across all modern web browsers, ensuring that your web applications will function consistently across different platforms.

Note: While browser support is robust, it’s always good practice to test event handlers on different browsers to guarantee uniformity. ✅

Conclusion

The onkeyup event is a vital part of interactive web development, allowing developers to capture and respond to key release actions effectively. By understanding the syntax, attributes, and key differences between onkeyup and other keyboard events, you can build highly responsive and engaging web applications. From form validation to real-time canvas interactions, the onkeyup event is an essential tool in your JavaScript toolkit.