JavaScript and TypeScript course ยท Module 8: Events and the DOM
Events and Interactions in JavaScript
In this lesson3
"Welcome back to Jurassic Park," greets you Ray Arnold, the chief systems engineer. "Today I'll show you how the most critical aspect of our systems works - interactivity. Every system in the park, from the security gates to the dinosaur monitoring, must respond to various signals in real time."
Ray leads you to the central control panel, where hundreds of indicators blink and pulse. "Look," he points at the screen, "all these systems listen for events - a gate opening, movement in an enclosure, a temperature change. In JavaScript, we work exactly the same way."
What Are Events in JavaScript?
Events are a fundamental communication mechanism in the browser. Every user interaction - a click, a mouse movement, a key press - generates an event that we can respond to.
// Similar to a motion sensor in a dinosaur enclosure
const motionSensor = document.getElementById('dino-enclosure');
motionSensor.addEventListener('click', function() {
console.log('Activity detected in the enclosure!');
checkDinosaurStatus();
});"In Jurassic Park," Ray continues, "we have thousands of sensors. Each one sends signals to the control center. If we had to constantly check every sensor, the system would collapse. Instead, sensors send events only when something happens."
The Browser Event Model
The browser implements a so-called Event-Driven Architecture - an architecture driven by events. This means that code doesn't execute sequentially from top to bottom, but reacts to events occurring in the system.
// Code registers listeners and waits for events
console.log('System active - listening...');
document.addEventListener('click', () => {
console.log('Click registered!');
});
document.addEventListener('keydown', () => {
console.log('Key pressed!');
});
// The program doesn't end - it waits for events
console.log('All systems ready');Types of Events
Ray shows you a list on the screen. "We have dozens of sensor types in the park. Similarly, JavaScript has dozens of event types:"
Mouse events:
click- click (like an emergency button)dblclick- double clickmouseenter/mouseleave- mouse entering/leavingmousemove- mouse movement (like a motion sensor)mousedown/mouseup- pressing/releasing a mouse button
Keyboard events:
keydown- key pressedkeyup- key releasedkeypress- deprecated, do not use it (usekeydownorinputinstead)
Form events:
submit- form submissionchange- field value changedinput- text inputfocus/blur- field activation/deactivation
Document events:
DOMContentLoaded- DOM ready (like a system going online)load- all resources loadedscroll- page scrollingresize- window resize
Anatomy of an Event
"Every event carries information with it," Ray explains, showing a detailed sensor report. "Similarly, every Event object in JavaScript contains data about what happened."
const enclosureMap = document.getElementById('park-map');
enclosureMap.addEventListener('click', function(event) {
// The event object contains detailed information
console.log('Event type:', event.type); // 'click'
console.log('Target element:', event.target); // the clicked element
console.log('Position X:', event.clientX); // X coordinate
console.log('Position Y:', event.clientY); // Y coordinate
console.log('Mouse button:', event.button); // 0=left, 1=middle, 2=right
console.log('Ctrl pressed?', event.ctrlKey); // true/false
console.log('Shift pressed?', event.shiftKey); // true/false
// We can use this information for precise reactions
if (event.ctrlKey) {
selectMultipleDinosaurs(event.target);
} else {
selectSingleDinosaur(event.target);
}
});Why Are Events Important?
Ray points to the large screen showing maps of all enclosures. "Without the event system, we'd have to check every sensor every second. That would be inefficient and resource-heavy. Events allow systems to react instantly and only when needed."
In web applications, events enable:
- Interactivity - responding to user actions
- Performance - code runs only when needed
- Asynchrony - different parts of the application can operate independently
- Modularity - different components can communicate through events
First Practical Example
"Let's see it in action," says Ray, opening a code panel. "Let's create a simple enclosure monitoring system."
// T-Rex enclosure monitoring system
const trexEnclosure = {
temperature: 28,
humidity: 65,
feedingSchedule: '14:00',
lastActivity: null,
initialize() {
// Registering listeners for various systems
const tempSensor = document.getElementById('temp-sensor');
const feedButton = document.getElementById('feed-button');
const activityMonitor = document.getElementById('activity-monitor');
// Temperature monitoring
tempSensor.addEventListener('change', (e) => {
this.temperature = parseFloat(e.target.value);
this.checkConditions();
});
// Feeding system
feedButton.addEventListener('click', () => {
this.feedDinosaur();
});
// Activity detection
activityMonitor.addEventListener('motion', (e) => {
this.lastActivity = new Date();
this.logActivity(e.detail);
});
console.log('T-Rex monitoring system active');
},
checkConditions() {
if (this.temperature > 35) {
this.triggerAlert('Temperature too high!', 'warning');
} else if (this.temperature < 20) {
this.triggerAlert('Temperature too low!', 'warning');
} else {
console.log('Conditions optimal');
}
},
feedDinosaur() {
console.log('Starting T-Rex feeding procedure...');
this.triggerAlert('Feeding in progress', 'info');
setTimeout(() => {
console.log('Feeding completed successfully');
this.triggerAlert('Feeding completed', 'success');
}, 3000);
},
logActivity(details) {
console.log(`Activity registered: ${details.type} at ${this.lastActivity.toLocaleTimeString()}`);
},
triggerAlert(message, level) {
const alertEvent = new CustomEvent('parkAlert', {
detail: { message, level, timestamp: new Date() }
});
document.dispatchEvent(alertEvent);
}
};
// System initialization
document.addEventListener('DOMContentLoaded', () => {
trexEnclosure.initialize();
});
// Central alert system
document.addEventListener('parkAlert', (e) => {
const { message, level, timestamp } = e.detail;
console.log(`[${timestamp.toLocaleTimeString()}] ${level.toUpperCase()}: ${message}`);
});Best Practices - Ray Arnold's Rules
"Through years of working on Jurassic Park systems," says Ray, "I've learned a few key rules:"
1. Always check if the element exists
const emergencyButton = document.getElementById('emergency');
if (emergencyButton) {
emergencyButton.addEventListener('click', evacuatePark);
} else {
console.error('CRITICAL ERROR: Emergency button not found!');
}2. Remove listeners when they're no longer needed
function setupTemporaryMonitoring() {
const sensor = document.getElementById('temp-sensor');
function handleReading(e) {
console.log('Reading:', e.target.value);
}
sensor.addEventListener('change', handleReading);
// After 1 hour, disable monitoring
setTimeout(() => {
sensor.removeEventListener('change', handleReading);
console.log('Monitoring ended');
}, 3600000);
}3. Use named functions for readability
The function's name tells you at once what the listener does, and when something goes wrong, you will see it in the call stack in the developer tools.
// Better
function handleEmergencyClick(event) {
console.log('Activating emergency protocol');
evacuatePark();
}
emergencyButton.addEventListener('click', handleEmergencyClick);
// Than
emergencyButton.addEventListener('click', function(e) {
console.log('Activating emergency protocol');
evacuatePark();
});4. Group similar events
class EnclosureMonitor {
constructor(enclosureId) {
this.enclosure = document.getElementById(enclosureId);
this.initializeEvents();
}
initializeEvents() {
// All event listeners in one place
this.enclosure.addEventListener('click', (e) => this.handleClick(e));
this.enclosure.addEventListener('mouseenter', (e) => this.handleMouseEnter(e));
this.enclosure.addEventListener('mouseleave', (e) => this.handleMouseLeave(e));
}
handleClick(event) {
console.log('Enclosure clicked');
}
handleMouseEnter(event) {
this.enclosure.classList.add('highlighted');
}
handleMouseLeave(event) {
this.enclosure.classList.remove('highlighted');
}
}Summary
"Events are the core of every interactive system," Ray summarizes. "Without them, our applications would be static and useless - like a park without security systems."
Key concepts:
- Events are generated by the browser in response to user actions
- addEventListener() allows you to listen for events
- The event object contains detailed information about the event
- Proper listener management is crucial for performance
In the following lessons, we'll dive deeper into advanced event handling techniques, learning about propagation, delegation, and custom events.
Code for this lesson: index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Jurassic Park - Alarm Panel</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
margin: 0;
padding: 20px;
color: white;
}
.emergency-panel {
max-width: 400px;
margin: 50px auto;
background: rgba(0, 0, 0, 0.8);
border-radius: 15px;
padding: 30px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
border: 2px solid #e74c3c;
}
.emergency-button {
width: 100%;
height: 100px;
background: linear-gradient(45deg, #e74c3c, #c0392b);
border: none;
border-radius: 10px;
color: white;
font-size: 24px;
font-weight: bold;
cursor: pointer;
transition: all 0.3s ease;
margin-bottom: 20px;
box-shadow: 0 5px 15px rgba(231, 76, 60, 0.4);
}
.emergency-button:hover {
transform: translateY(-2px);
box-shadow: 0 10px 25px rgba(231, 76, 60, 0.6);
background: linear-gradient(45deg, #c0392b, #a93226);
}
.emergency-button:active {
transform: translateY(0);
box-shadow: 0 5px 15px rgba(231, 76, 60, 0.4);
}
.status-display {
background: rgba(255, 255, 255, 0.1);
border-radius: 8px;
padding: 15px;
margin-top: 20px;
border: 1px solid rgba(255, 255, 255, 0.2);
}
.alert-message {
display: none;
background: #e74c3c;
color: white;
padding: 15px;
border-radius: 8px;
margin-top: 15px;
text-align: center;
font-weight: bold;
animation: pulse 1s infinite;
}
@keyframes pulse {
0% { opacity: 1; }
50% { opacity: 0.7; }
100% { opacity: 1; }
}
h1 {
text-align: center;
margin-bottom: 30px;
color: #ecf0f1;
}
.last-activation {
color: #bdc3c7;
font-size: 14px;
}
</style>
</head>
<body>
<div class="emergency-panel">
<h1>T-REX ALARM PANEL</h1>
<button id="emergency-button" class="emergency-button">
ACTIVATE EMERGENCY ALARM
</button>
<div class="status-display">
<div>System status: <span id="system-status">READY</span></div>
<div class="last-activation">Last activation: <span id="last-activation">NEVER</span></div>
</div>
<div id="alert-message" class="alert-message">
ALARM! T-REX ESCAPED FROM THE PADDOCK!
</div>
</div>
<script>
// Getting references to DOM elements
const emergencyButton = document.getElementById('emergency-button');
const systemStatus = document.getElementById('system-status');
const lastActivation = document.getElementById('last-activation');
const alertMessage = document.getElementById('alert-message');
// Adding an event listener to the button
emergencyButton.addEventListener('click', function() {
// Displaying alert
alert('EMERGENCY ALARM ACTIVATED!\n\nT-Rex escaped from the paddock!\nEvacuation in progress...');
// Updating the system status
systemStatus.textContent = 'ALARM ACTIVE';
systemStatus.style.color = '#e74c3c';
// Saving the time of the last activation
const now = new Date();
lastActivation.textContent = now.toLocaleTimeString('en-US');
// Showing the alarm message
alertMessage.style.display = 'block';
// Changing the button text
emergencyButton.textContent = 'ALARM ACTIVE';
emergencyButton.style.background = 'linear-gradient(45deg, #27ae60, #2ecc71)';
// After 5 seconds we reset the system
setTimeout(function() {
systemStatus.textContent = 'READY';
systemStatus.style.color = '#2ecc71';
alertMessage.style.display = 'none';
emergencyButton.textContent = 'ACTIVATE EMERGENCY ALARM';
emergencyButton.style.background = 'linear-gradient(45deg, #e74c3c, #c0392b)';
}, 5000);
});
// Adding mouse hover handling
emergencyButton.addEventListener('mouseenter', function() {
console.log('Cursor over the emergency button - CAUTION!');
});
emergencyButton.addEventListener('mouseleave', function() {
console.log('Cursor left the emergency button');
});
</script>
</body>
</html>Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Which method is the primary method for handling events in JavaScript?