iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

CategoryEvents
Mouseclick, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, contextmenu
Pointer / touchpointerdown, pointerup, pointermove, touchstart, touchend
Keyboardkeydown, keyup, keypress (deprecated)
Formsubmit, reset, change, input, focus, blur, invalid
Document & windowDOMContentLoaded, load, resize, scroll, visibilitychange, beforeunload
Drag & dropdragstart, dragover, drop, dragend
Mediaplay, pause, ended, timeupdate, volumechange
Networkonline, 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>

Test yourself

Q1. Modern event attach uses…
Q2. Stop default browser action with…
Q3. Event delegation listens on…

Discussion

Loading…