aScript Event Handling: Simple Exercises and Solutions
Here are some basic exercises to practice event handling in JavaScript, along with
their solutions.
Exercise 1: Button Click Alert
Task: Create a button that shows an alert when clicked.
html
<!-- HTML -->
<button id="alertButton">Click Me!</button>
javascript
// Solution
[Link]('alertButton').addEventListener('click', function() {
alert('Button was clicked!');
});
Exercise 2: Change Background Color
Task: Create a button that changes the background color of the page when clicked.
html
<button id="colorButton">Change Color</button>
javascript
// Solution
[Link]('colorButton').addEventListener('click', function() {
[Link] = 'lightblue';
});
Exercise 3: Toggle Visibility
Task: Create a button that toggles the visibility of a paragraph.
html
<button id="toggleButton">Toggle Text</button>
<p id="toggleText">This text will show/hide.</p>
javascript
// Solution
[Link]('toggleButton').addEventListener('click', function() {
const text = [Link]('toggleText');
[Link] = [Link] === 'none' ? 'block' : 'none';
});
Exercise 4: Input Character Counter
Task: Show a live count of characters as the user types in a text input.
html
<input type="text" id="textInput">
<p>Character count: <span id="charCount">0</span></p>
javascript
// Solution
[Link]('textInput').addEventListener('input', function() {
const count = [Link];
[Link]('charCount').textContent = count;
});
Exercise 5: Mouse Position Tracker
Task: Display the current mouse coordinates as the user moves the mouse over a div.
html
<div id="trackerArea" style="height: 200px; border: 1px solid black;">
Move your mouse here
</div>
<p>Coordinates: <span id="coordinates">0, 0</span></p>
javascript
// Solution
[Link]('trackerArea').addEventListener('mousemove', function(e) {
[Link]('coordinates').textContent = `${[Link]}, $
{[Link]}`;
});
Exercise 6: Form Submission Prevention
Task: Prevent a form from submitting and show the input value instead.
html
<form id="myForm">
<input type="text" id="nameInput" placeholder="Enter your name">
<button type="submit">Submit</button>
</form>
<p id="formResult"></p>
javascript
// Solution
[Link]('myForm').addEventListener('submit', function(e) {
[Link](); // Prevent form submission
const name = [Link]('nameInput').value;
[Link]('formResult').textContent = `Hello, ${name}!`;
});
Exercise 7: Double Click Event
Task: Change the text of a button when it's double-clicked.
html
<button id="doubleClickButton">Double Click Me</button>
javascript
// Solution
[Link]('doubleClickButton').addEventListener('dblclick',
function() {
[Link] = 'You double-clicked me!';
});
Exercise 8: Key Press Logger
Task: Show the last key pressed by the user.
html
<p>Press any key: <span id="keyDisplay">None yet</span></p>