Home / Learn HTML / HTML Event Attributes

HTML Event Attributes

Events tell your page that something happened: a click, a key, a mouse move, a form change.

Definition

An event is something that happens on the page: a click, a key press, a form submit, the page finishing loading. HTML lets you attach JavaScript to an event with an event attribute such as onclick. The modern way is addEventListener in a script, which keeps HTML and code apart.

GroupExamples
Mouseclick, dblclick, mouseover, mouseout, contextmenu
Keyboardkeydown, keyup
Formsubmit, change, input, focus, blur, reset
Pageload, DOMContentLoaded, resize, scroll
Dragdragstart, dragover, drop
Mediaplay, pause, ended, timeupdate

Theory in plain words

Event handlingUser actsEvent firesHandler runsUI changes
Event handling

What it is

Event attributes such as onclick and onchange run JavaScript when something happens to an element.

Why we use it

They connect user actions to code.

How it works

The browser fires an event, then runs the handler. Modern code prefers addEventListener over attributes.

Where it is used

  • Buttons and forms
  • Keyboard shortcuts
  • Page load actions
onclickTry it Yourself
ondblclickTry it Yourself
onmouseover and onmouseoutTry it Yourself
onmousedown and onmouseupTry it Yourself
onkeydownTry it Yourself
onkeyupTry it Yourself
oninputTry it Yourself
onchangeTry it Yourself
onfocus and onblurTry it Yourself
onsubmitTry it Yourself
onload on an imageTry it Yourself
onerror on an imageTry it Yourself
oncopyTry it Yourself
onscrollTry it Yourself
oncontextmenu (right click)Try it Yourself
ondrag and ondropTry it Yourself
addEventListener (better way)Try it Yourself

This keeps JavaScript out of your HTML.

Quick quiz

1. Which event fires on a click?

2. Which event fires on every typed change?

3. Which is the better way to attach events?

Common questions

Which event fires on a click?

onclick. onclick.

Which event fires on every typed change?

oninput. oninput fires as you type.

Which is the better way to attach events?

addEventListener. It keeps HTML clean.

My notes
Ask a question about this lesson