HTML Events
An HTML event is something that happens to an element — a click, a key press, the page finishing loading. JavaScript attaches handlers to events with addEventListener.
Common events
| Category | Events |
|---|---|
| Mouse | click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, contextmenu |
| Pointer / touch | pointerdown, pointerup, pointermove, touchstart, touchend |
| Keyboard | keydown, keyup, keypress (deprecated) |
| Form | submit, reset, change, input, focus, blur, invalid |
| Document & window | DOMContentLoaded, load, resize, scroll, visibilitychange, beforeunload |
| Drag & drop | dragstart, dragover, drop, dragend |
| Media | play, pause, ended, timeupdate, volumechange |
| Network | online, offline |
Attaching a handler
const btn = document.querySelector('button');
btn.addEventListener('click', function (event) {
console.log('clicked at', event.clientX, event.clientY);
});
Tip: Prefer
addEventListener over inline onclick="…" attributes. You can attach multiple handlers, remove them later, and keep behaviour out of your HTML.Example
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML Events</title>
</head>
<body>
<h1>HTML Events</h1>
<p>This is a demo page for the "HTML Events" lesson.</p>
</body>
</html>
Try it Yourself »
Exercise
Add the attribute that runs JS when the button is clicked.
<button
="alert('hi')">Tap</button>
"on" + the event name.
Discussion
Loading…