HTML event attributes allow you to attach inline JavaScript code directly to HTML tags, triggering functions when users click elements, change inputs, submit forms, or press keyboard keys.
Event attributes begin with the prefix on followed by the event name:
<!-- Mouse Click Event -->
<button onclick="alert('Button Clicked!')">Click Me</button>
<!-- Form Change & Focus Events -->
<input type="text" onchange="validateInput()" onfocus="highlightField()">
<!-- Keyboard Event -->
<input type="text" onkeydown="handleKeyPress(event)">
Primary event attribute categories:
onclick, ondblclick, onmouseover, onmouseout, onmousedown.onchange, oninput, onsubmit, onfocus, onblur.onkeydown, onkeyup, onkeypress.onload, onresize, onscroll, onunload.flowchart LR
A["User Action (Mouse Click / Key Press)"] --> B["Browser Fires Event (onclick)"]
B --> C["Executes Inline JS Function Callback"]
C --> D["DOM Updates Visually"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML Event Attributes Example</title>
</head>
<body style="font-family: system-ui, sans-serif; background-color: #0f172a; color: #f8fafc; padding: 2rem;">
<h2>Live Input Mirror</h2>
<div style="background-color: #1e293b; padding: 1.5rem; border-radius: 8px; max-width: 400px;">
<label for="text-input" style="display: block; margin-bottom: 0.5rem;">Type Something:</label>
<!-- Live input event listener -->
<input
type="text"
id="text-input"
oninput="document.getElementById('output').textContent = this.value"
style="width: 100%; padding: 8px; border-radius: 4px; border: 1px solid #334155; margin-bottom: 1rem;">
<p>Live Output: <span id="output" style="color: #38bdf8; font-weight: bold;"></span></p>
</div>
</body>
</html>
element.addEventListener() in external JS files.oninput for instant text updates and onchange for finalized selections: oninput fires continuously as text is typed; onchange fires when focus leaves the input field.false in onsubmit to prevent page reloads during AJAX calls: onsubmit="submitForm(event); return false;" stops default browser submission behavior.Create a <button> element with an onclick attribute that changes its own text to "Submitted!" when clicked!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.