HTML Event Attributes: onclick, onsubmit, and Event Handling

Reference all HTML event attributes for mouse, keyboard, form, drag-and-drop, touch, and animation events. Understand inline handlers vs addEventListener patterns.

Event Handling

Detailed Explanation

HTML Event Attributes

HTML event attributes allow you to attach event handlers directly to elements. While inline event handlers are available on every HTML element, modern best practice recommends using addEventListener in JavaScript instead.

Mouse Events

<button onclick="handleClick()" onmouseenter="highlight()" onmouseleave="unhighlight()">
  Click me
</button>
Attribute Fires when
onclick Element is clicked
ondblclick Element is double-clicked
onmousedown Mouse button pressed
onmouseup Mouse button released
onmouseover Pointer enters element
onmouseout Pointer leaves element
onmousemove Pointer moves within element
oncontextmenu Right-click context menu

Keyboard Events

<input onkeydown="checkKey(event)" onkeyup="validate()">

Form Events

<form onsubmit="return validateForm()" onreset="clearErrors()">
  <input oninput="liveValidate()" onchange="saveValue()" oninvalid="showError()">
</form>

Modern Approach: addEventListener

<!-- Inline (not recommended for production) -->
<button onclick="doSomething()">Click</button>

<!-- addEventListener (recommended) -->
<button id="myBtn">Click</button>
<script>
  document.getElementById('myBtn').addEventListener('click', (e) => {
    // Handle click
  });
</script>

Why addEventListener is Preferred

  1. Separation of concerns — HTML for structure, JS for behavior
  2. Multiple handlers — Can attach multiple listeners to one event
  3. Event options — Supports capture, once, passive, and signal options
  4. CSP compliance — Content Security Policy can block inline handlers
  5. Testability — Easier to unit test separate handler functions

Use Case

Event handling is fundamental to any interactive web application. While inline event attributes are useful for quick prototyping and simple interactions, production applications should use addEventListener for better security (CSP compliance), maintainability, and testability. Understanding both approaches is important for reading legacy code and writing modern JavaScript.

Try It — HTML Element Reference

Open full tool