Introduction
In this lab, participants will learn how to handle keyboard events in a web page by creating an interactive HTML interface that responds to user keystrokes. The lab focuses on implementing event handlers such as onkeydown and onkeyup to dynamically change text color and demonstrate real-time keyboard interaction. Participants will start by setting up a structured HTML document with an input element and styling, then progressively add JavaScript functionality to capture and respond to keyboard events.
The lab provides a hands-on approach to understanding keyboard event management, covering key techniques like detecting key presses, modifying page elements, and implementing event listeners. By following the step-by-step process, learners will gain practical experience in creating responsive web interfaces that can detect and react to user keyboard interactions, enhancing their understanding of client-side event handling in web development.
Set Up HTML Structure with Input Element
In this step, we'll create the basic HTML structure for our keyboard event handling lab. We'll set up an HTML file with an input element that will serve as the target for our keyboard events.
Open the WebIDE and create a new file named index.html in the ~/project directory. We'll start by creating a simple HTML5 document with a basic structure and an input element.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Keyboard Events Lab</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
.container {
text-align: center;
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
input {
padding: 10px;
font-size: 16px;
width: 300px;
margin-bottom: 10px;
}
#output {
margin-top: 10px;
font-weight: bold;
}
</style>
</head>
<body>
<div class="container">
<h1>Keyboard Events Lab</h1>
<input type="text" id="keyboardInput" placeholder="Type something here" />
<div id="output"></div>
</div>
</body>
</html>
Let's break down the key components of this HTML structure:
- We've created a simple, centered layout with a container div.
- An
<input>element with the IDkeyboardInputis added as the main interaction point. - A
<div>with IDoutputis included to display event-related information. - Basic CSS is added to improve the visual appearance and layout.
This initial setup provides a clean, user-friendly interface for our keyboard event demonstration. In the subsequent steps, we'll add JavaScript to handle keyboard events on this input element.
Implement onkeydown Event to Change Text Color
In this step, we'll add JavaScript to implement the onkeydown event handler for our input element. This event will change the text color when a key is pressed down.
Open the index.html file in the WebIDE and add a <script> tag just before the closing </body> tag to include our JavaScript code:
<script>
// Get references to the input element and output div
const inputElement = document.getElementById("keyboardInput");
const outputElement = document.getElementById("output");
// Add onkeydown event listener to change text color
inputElement.onkeydown = function (event) {
// Change the input text color to red when a key is pressed
this.style.color = "red";
// Display information about the key pressed
outputElement.textContent = `Key pressed: ${event.key} (KeyCode: ${event.keyCode})`;
};
</script>
Let's break down the key parts of this code:
document.getElementById()is used to get references to the input and output elements.inputElement.onkeydownadds an event listener for the keydown event.- Inside the event handler:
this.style.color = 'red'changes the text color to red when a key is pressed.outputElement.textContentdisplays information about the key pressed.
Example output when you type in the input field:
- The text will turn red as you type
- The output div will show the last key pressed and its keyCode
This demonstrates how the onkeydown event works:
- It triggers every time a key is pressed down
- Provides access to event details like the key pressed
- Allows dynamic manipulation of element styles
Implement onkeyup Event to Restore Original Text Color
In this step, we'll add the onkeyup event handler to restore the input text color to its original state when the key is released. We'll modify the existing script in the index.html file to include this functionality.
Update the <script> section in your index.html file with the following code:
<script>
// Get references to the input element and output div
const inputElement = document.getElementById("keyboardInput");
const outputElement = document.getElementById("output");
// Add onkeydown event listener to change text color
inputElement.onkeydown = function (event) {
// Change the input text color to red when a key is pressed
this.style.color = "red";
// Display information about the key pressed
outputElement.textContent = `Key pressed: ${event.key} (KeyCode: ${event.keyCode})`;
};
// Add onkeyup event listener to restore original text color
inputElement.onkeyup = function (event) {
// Restore the input text color to black when the key is released
this.style.color = "black";
// Update the output with key release information
outputElement.textContent = `Key released: ${event.key} (KeyCode: ${event.keyCode})`;
};
</script>
Let's break down the new onkeyup event handler:
inputElement.onkeyupadds an event listener for the keyup event.- Inside the event handler:
this.style.color = 'black'restores the text color to black when a key is released.outputElement.textContentdisplays information about the key released.
Example interaction:
- When you press a key, the text turns red
- When you release the key, the text returns to black
- The output div shows details about both key press and release events
This demonstrates the difference between onkeydown and onkeyup events:
onkeydowntriggers when a key is pressed downonkeyuptriggers when a key is released- Both events provide access to key information
Add Window Onload Event Handler
In this step, we'll introduce the window.onload event handler to demonstrate how to execute JavaScript code after the entire web page has finished loading. We'll add an initialization function that provides an initial message and sets up some default styling.
Update the <script> section in your index.html file with the following code:
<script>
// Window onload event handler
window.onload = function () {
// Get references to the input element and output div
const inputElement = document.getElementById("keyboardInput");
const outputElement = document.getElementById("output");
// Set initial message when page loads
outputElement.textContent = "Page loaded! Start typing in the input field.";
outputElement.style.color = "green";
// Add onkeydown event listener to change text color
inputElement.onkeydown = function (event) {
// Change the input text color to red when a key is pressed
this.style.color = "red";
// Display information about the key pressed
outputElement.textContent = `Key pressed: ${event.key} (KeyCode: ${event.keyCode})`;
outputElement.style.color = "blue";
};
// Add onkeyup event listener to restore original text color
inputElement.onkeyup = function (event) {
// Restore the input text color to black when the key is released
this.style.color = "black";
// Update the output with key release information
outputElement.textContent = `Key released: ${event.key} (KeyCode: ${event.keyCode})`;
outputElement.style.color = "green";
};
};
</script>
Key changes in this step:
- Wrapped existing event handlers inside
window.onloadfunction - Added an initial message when the page loads
- Introduced color changes to the output element for better visual feedback
The window.onload event ensures that:
- All page elements are fully loaded before running JavaScript
- Prevents errors that might occur if scripts run before DOM is ready
- Provides a reliable way to initialize page functionality
Example interaction:
- When page loads, you'll see a green "Page loaded!" message
- Typing will change text colors and output messages
- Key press shows blue messages
- Key release shows green messages
Test and Verify Keyboard Event Interactions
In this final step, we'll test and verify the keyboard event interactions we've implemented throughout the lab. We'll explore different scenarios to demonstrate how our event handlers work and understand their behavior.
Open the index.html file in the WebIDE and ensure you have the complete script from previous steps. Now, let's test various keyboard interactions:
Page Load Interaction
- When the page loads, you should see a green message: "Page loaded! Start typing in the input field."
Key Press Interactions
- Type any key in the input field
- Observe the following changes:
- Text color changes to red
- Output message shows the key pressed and its keyCode
- Output message color changes to blue
Key Release Interactions
- Release the key you pressed
- Observe the following changes:
- Text color returns to black
- Output message shows the key released and its keyCode
- Output message color returns to green
Example interaction scenarios:
Scenario 1: Typing "Hello"
- First 'H' pressed: Text turns red, blue output message
- 'H' released: Text turns black, green output message
- Continue for each letter...
Scenario 2: Special keys
- Try arrow keys, shift, ctrl, etc.
- Observe how different keys trigger events
Key Learning Points:
onkeydown: Triggers when a key is pressed downonkeyup: Triggers when a key is releasedwindow.onload: Ensures page is fully loaded before running scripts
To complete the lab:
- Open the HTML file in a web browser
- Interact with the input field
- Observe color and message changes
- Verify all event handlers work as expected
Summary
In this lab, participants learn to handle keyboard events in a web page by creating an interactive HTML interface with JavaScript event listeners. The lab begins by setting up a structured HTML document featuring an input element and an output div, styled with responsive CSS to provide a clean, centered user interface. Participants will explore key event handling techniques such as onkeydown and onkeyup, which allow dynamic manipulation of text color and real-time event tracking.
The learning objectives focus on understanding browser event mechanisms, implementing event listeners, and creating responsive web interactions. By working through the lab steps, developers will gain practical experience in capturing keyboard inputs, modifying page elements dynamically, and implementing window-level event handlers, which are fundamental skills for creating interactive and engaging web applications.



