HTML•DOM Events
DOM Event Listeners: addEventListener, Click, and Input Events
Learn modern event-driven programming in browser JavaScript with addEventListener.
Syntax
element.addEventListener("click", (event) => {});
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| addEventListener() | Method | Attaches an event handler function to an element. |
| event.target | Property | Reference to the element that dispatched the event. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing HTML locally:
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; padding: 20px; }
input { padding: 8px; border: 1px solid #cbd5e1; border-radius: 6px; width: 220px; }
.counter { margin-top: 10px; font-weight: bold; color: #475569; }
</style>
</head>
<body>
<h2>Real-Time Input Character Counter</h2>
<input type="text" id="user-input" placeholder="Type something..." />
<div class="counter">Characters: <span id="char-count">0</span></div>
<script>
const inputField = document.querySelector("#user-input");
const countDisplay = document.querySelector("#char-count");
// Real-time input event
inputField.addEventListener("input", (e) => {
countDisplay.textContent = e.target.value.length;
});
</script>
</body>
</html>Expected Output:
[Interactive UI: Typing in the Input Updates Character Count in Real Time]
How It Works: Step-by-Step
- Lines 17-21: addEventListener("input") captures real-time character typing events.
- Line 20: e.target.value.length updates count span.
Key Concepts
- The "input" event fires immediately on every keystroke, paste, or cut.
- Multiple event listeners can be attached to the same element without overwriting.
Common Mistake: Using legacy onclick property instead of addEventListener
element.onclick = fn overwrites any previous handler, preventing modularity. Use addEventListener.
❌ Incorrect
btn.onclick = handler1; btn.onclick = handler2; // Overwrites handler1!
✅ Correct
btn.addEventListener("click", handler1); btn.addEventListener("click", handler2);Related HTML Tutorials & Compiler
DOM Manipulation: querySelector, textContent, and innerHTML
Select and manipulate HTML elements using document.querySelector and textContent.
DOM classList API: add, remove, and toggle CSS Classes
Mutate styles dynamically by toggling CSS classes with element.classList.
Dynamic DOM: document.createElement and appendChild
Generate dynamic HTML elements on the fly with document.createElement and append.
HTML Online Compiler
Open in Compilra IDE
Run and test HTML on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.