Skip to content
Tutorials Center
My learning

Topics

HTML Reference ยท Attributes and Events

HTML event attributes

Every HTML on* event handler attribute grouped by category: window, form, keyboard, mouse, pointer, drag, clipboard, media and more, with live examples.

Event handler attributes run JavaScript when something happens to an element: a click, a key press, a form submission, a video ending. Each one is the event name with on in front: the click event has onclick, the input event has oninput. They are global, so any element accepts them, although many events only ever fire on certain elements.

HTML
<button onclick="alert('Saved')">Save</button>

Prefer addEventListener() in real projects. Inline on* attributes mix behavior into markup, allow only one handler per event, run code from a string in the global scope, and are blocked by any Content Security Policy that doesn't allow 'unsafe-inline' (which a good CSP never does). The same code written with addEventListener() keeps working under a strict CSP:

JavaScript
document.querySelector('#save').addEventListener('click', () => alert('Saved'));

The tables below use the attribute name, but every event listed can be used with addEventListener() by dropping the on ('click', 'keydown', 'submit'). Event names are all lowercase.

Try it

Inline handler vs addEventListener

Inside an inline handler, this is the element and event is the event object, so onclick="console.log(event.type)" works. Returning false from an inline handler cancels the default action, but calling event.preventDefault() is clearer.

Window and document events

These fire on the window. As attributes, they go on <body>, which forwards them to the window.

Attribute Fires when
onafterprint The print dialog has closed or printing has started.
onbeforeprint Printing is about to start, before the print preview is built.
onbeforeunload The page is about to be unloaded. Calling preventDefault() asks the browser to show a "Leave site?" confirmation.
onerror A script error reaches the window (on <body>), or a resource such as an image or script fails to load (on that element).
onhashchange The #fragment part of the URL changes.
onlanguagechange The user's preferred languages change.
onload The page and all its resources (images, styles, frames) have finished loading. On <img>, <script>, <iframe> and <link>, fires when that resource loads.
onmessage The window receives a message through postMessage().
onmessageerror A received message can't be deserialized.
onoffline The browser loses its network connection.
ononline The browser regains its network connection.
onpagehide The user navigates away and the page is hidden (it may be kept in the back/forward cache).
onpagereveal Newer. The page is about to render its first frame after loading or being restored from the back/forward cache.
onpageshow The page is shown, including when restored from the back/forward cache (event.persisted is true).
onpageswap Newer. The page is about to be replaced by a navigation; useful for view transitions across documents.
onpopstate The active history entry changes, for example with the Back button after history.pushState().
onrejectionhandled A rejected promise gets a handler late, after unhandledrejection already fired.
onresize The viewport is resized.
onscroll The document is scrolled (also fires on any scrollable element).
onstorage localStorage is changed by another tab or window of the same origin.
onunhandledrejection A promise is rejected and nothing handles it.
onunload Deprecated. The page is being unloaded. It breaks the back/forward cache; use onpagehide instead.

Some document-level events have no attribute and work only with addEventListener(): DOMContentLoaded (the HTML is parsed) and the document events readystatechange and visibilitychange (use document.onvisibilitychange or a listener, not a <body> attribute).

Form events

Attribute Fires when
onbeforeinput The value of an editable field or contenteditable element is about to change. Cancelable.
onchange The user commits a change: picks an option, toggles a checkbox, or leaves a text field after editing it.
onformdata A <form> builds its data set for submission; event.formData can be edited.
oninput The value changes, on every keystroke or adjustment.
oninvalid A control fails validation when the form is submitted or checkValidity() is called.
onreset A form is reset.
onselect Text is selected inside an <input> or <textarea>.
onsubmit A form is submitted. Call event.preventDefault() to handle it with JavaScript instead.

Focus events

Attribute Fires when
onblur The element loses focus. Doesn't bubble.
onfocus The element receives focus. Doesn't bubble.

The bubbling versions, focusin and focusout, have no widely supported attributes. Use addEventListener('focusin', โ€ฆ).

Keyboard events

Attribute Fires when
onkeydown A key is pressed. Repeats while held (event.repeat is true). Read event.key for the character or key name, such as "a", "Enter" or "ArrowLeft".
onkeyup A key is released.
onkeypress Deprecated. A character-producing key is pressed. Use onkeydown or onbeforeinput.

Mouse events

Attribute Fires when
onauxclick A non-primary button (usually the middle button) is clicked.
onclick The primary button is clicked, or a button or link is activated with the keyboard (Enter or Space).
oncontextmenu The context menu is requested (right-click or the Menu key). Cancelable.
ondblclick The element is double-clicked.
onmousedown A mouse button is pressed over the element.
onmouseenter The pointer moves onto the element. Doesn't bubble and ignores movement between children.
onmouseleave The pointer leaves the element. Doesn't bubble.
onmousemove The pointer moves over the element. Fires very often.
onmouseout The pointer leaves the element or moves onto one of its children. Bubbles.
onmouseover The pointer enters the element or one of its children. Bubbles.
onmouseup A mouse button is released over the element.
onwheel A wheel or trackpad scroll gesture happens over the element.

Pointer and touch events

Pointer events (from the Pointer Events specification) cover mouse, pen and touch with one API, and are usually a better choice than separate mouse and touch handlers.

Attribute Fires when
onpointerdown A pointer becomes active: button pressed, finger down, pen touches.
onpointerup A pointer is no longer active.
onpointermove A pointer changes position or pressure.
onpointerover / onpointerout A pointer enters or leaves the element or a child. Bubbles.
onpointerenter / onpointerleave A pointer enters or leaves the element itself. Doesn't bubble.
onpointercancel The browser takes over the pointer, for example to start scrolling.
ongotpointercapture / onlostpointercapture The element gains or loses pointer capture (setPointerCapture()).
ontouchstart / ontouchmove / ontouchend / ontouchcancel Touch Events: a finger touches, moves, lifts, or the touch is interrupted. Exposed mainly on touch devices.

Drag and drop events

Attribute Fires when
ondragstart The user starts dragging an element. Set the payload with event.dataTransfer.setData().
ondrag The dragged element moves (fires repeatedly).
ondragend The drag ends, whether it was dropped or canceled.
ondragenter A dragged item enters a possible drop target.
ondragover A dragged item is over a drop target (fires repeatedly). Call preventDefault() here to allow dropping.
ondragleave A dragged item leaves a drop target.
ondrop The item is dropped on a target that accepted it.

Clipboard and selection events

Attribute Fires when
oncopy The user copies content. Cancelable; event.clipboardData can replace what is copied.
oncut The user cuts content.
onpaste The user pastes content. Read it with event.clipboardData.getData('text').
onselectstart The user starts selecting text. Cancelable.
onselectionchange The text selection changes. Fires on document and, in newer browsers, on <input> and <textarea>.

Media events

For <audio> and <video>. They don't bubble.

Attribute Fires when
onabort Loading stops before the media is fully loaded, but not because of an error.
oncanplay Enough data is loaded to start playing, though it may stop to buffer.
oncanplaythrough The browser estimates it can play to the end without buffering.
ondurationchange The duration value changes, usually once the metadata loads.
onemptied The media is reset, for example when load() is called again.
onended Playback reaches the end.
onerror The media fails to load.
onloadeddata The first frame is available.
onloadedmetadata Duration and dimensions are known.
onloadstart The browser starts loading the media.
onpause Playback is paused.
onplay Playback is requested (after play() or the autoplay attribute).
onplaying Playback actually starts or resumes after buffering.
onprogress The browser is downloading media data.
onratechange The playback speed changes.
onseeked A seek operation finishes.
onseeking A seek operation starts.
onstalled Data is unexpectedly not arriving.
onsuspend Loading is intentionally paused by the browser.
ontimeupdate currentTime changes during playback (several times a second).
onvolumechange Volume or muted state changes.
onwaiting Playback stops because the next frame isn't loaded yet.
oncuechange On <track>: the active caption or subtitle cues change.

Interactive element and popover events

Attribute Fires when
onbeforematch Content with hidden="until-found" is about to be revealed by find-in-page or a fragment link.
onbeforetoggle A popover or <dialog> is about to open or close. event.newState is "open" or "closed".
oncancel A <dialog> is about to close because the user pressed Esc (cancelable); also fires on a file <input> when the picker is dismissed.
onclose A <dialog> has closed.
oncommand New. An element receives a command from a button with commandfor and command.
ontoggle A <details> element, popover or dialog has opened or closed.

Animation, transition and scrolling events

Attribute Fires when
onanimationstart / onanimationiteration / onanimationend / onanimationcancel A CSS animation starts, repeats, finishes or is aborted.
ontransitionrun / ontransitionstart / ontransitionend / ontransitioncancel A CSS transition is created, starts after its delay, finishes or is canceled.
onscrollend Scrolling of the element or document has finished.

Other events

Attribute Fires when
oncontextlost / oncontextrestored A <canvas> 2D context is lost (for example after a GPU reset) or restored.
onsecuritypolicyviolation A Content Security Policy blocks something on the page.
onslotchange On a <slot>: the nodes assigned to it change.

More examples

Form and keyboard events
Pointer events and media events