Skip to main content

HTML References

Event Attributes

Written by Updated Event Attributes exercises

Event attributes run JavaScript when something happens: a click, a key press, a form being sent. Add onclick to a button and you have your first interactive page. They are also the old way of doing it, and it helps to know why.

What is an Event?

An event is something that happens in the browser, caused by the user or by the page itself:

  • A user clicks a button: onclick
  • The page finishes loading: onload
  • A user presses a key: onkeydown
  • A form is sent: onsubmit
  • The mouse moves over an element: onmouseover

Every event attribute is the event name with on in front.

Basic Syntax

html

<element event="JavaScript code"></element>

Example:

html

<button onclick="alert('Button clicked!')">Click Me</button>

Click the button and an alert box pops up. The JavaScript inside the quotes runs every time the event happens.

Common Event Attributes

Event attributeRuns whenExample
onclickThe element is clicked<button onclick="myFunction()">Click</button>
onloadThe page or an image has finished loading<body onload="init()">
onchangeA form field's value changes and the field loses focus<input onchange="checkValue()">
oninputThe value changes, on every keystroke<input oninput="showLength()">
onmouseoverThe mouse pointer moves onto the element<div onmouseover="highlight()">Hover</div>
onmouseoutThe mouse pointer leaves the element<div onmouseout="removeHighlight()">Move out</div>
onkeydownA key is pressed<input onkeydown="keyPress()">
onfocusA field gets the keyboard focus<input onfocus="highlightField()">
onblurA field loses focus<input onblur="removeHighlight()">
onsubmitA form is about to be sent<form onsubmit="return validateForm()">

Example 1: Click Event

html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Event Example</title>
  <script>
    function showMessage() {
      alert("You clicked the button!");
    }
  </script>
</head>
<body>
  <button onclick="showMessage()">Click Me</button>
</body>
</html>

The button calls a function defined in the <script> block. Calling a function keeps the attribute short, which is easier to read than writing a whole script inside the quotes.

Example 2: Form Validation Event

html

<form onsubmit="return validateForm()">
  <input type="text" id="name" placeholder="Enter your name">
  <button type="submit">Submit</button>
</form>

<script>
  function validateForm() {
    let name = document.getElementById('name').value;
    if (name === "") {
      alert("Please enter your name!");
      return false;
    }
    alert("Form submitted successfully!");
    return true;
  }
</script>

If the name field is empty, the function returns false and the form is not sent. The return in onsubmit="return validateForm()" matters: without it, the form is sent anyway.

Example 3: Mouse Events

html

<div onmouseover="this.style.background='lightgreen'" 
     onmouseout="this.style.background='white'"
     style="width:200px; height:100px; border:1px solid gray; text-align:center; line-height:100px;">
  Hover over me!
</div>

The box turns light green when the mouse is over it and white again when it leaves. Inside an event attribute, this is the element itself.

Event Categories

CategoryExamples
Mouse Eventsonclick, ondblclick, onmouseover, onmouseout, onmousemove
Keyboard Eventsonkeydown, onkeypress, onkeyup
Form Eventsonsubmit, onchange, onfocus, onblur
Window Eventsonload, onresize, onscroll, onunload

The better way: addEventListener

Event attributes work, but in real projects they are avoided. They mix JavaScript into HTML, you can only attach one handler per event, and strict security settings (a Content Security Policy) block them completely. The modern way keeps the HTML clean and adds the behavior from JavaScript:

The same click, with addEventListener

html

<button id="clickBtn">Click Me</button>

<script>
  document.getElementById("clickBtn").addEventListener("click", function () {
    alert("Hello, World!");
  });
</script>

Note the event name loses the on: onclick becomes "click". The full story is in JavaScript addEventListener.

Complete HTML Event Attributes Reference

Mouse Events

Event AttributeDescription
onclickTriggered when an element is clicked.
ondblclickTriggered when an element is double-clicked.
onmousedownTriggered when a mouse button is pressed down.
onmouseupTriggered when a mouse button is released.
onmouseoverTriggered when the mouse pointer enters an element.
onmouseoutTriggered when the mouse pointer leaves an element.
onmousemoveTriggered when the mouse is moved within an element.
onwheelTriggered when the mouse wheel is scrolled.
oncontextmenuTriggered when the right mouse button is clicked (opens context menu).

Keyboard Events

Event AttributeDescription
onkeydownTriggered when a key is pressed down.
onkeypressTriggered when a key is pressed (deprecated in HTML5).
onkeyupTriggered when a key is released.

Form Events

Event AttributeDescription
oninputTriggered when user input is received.
onchangeTriggered when an element’s value changes.
onsubmitTriggered when a form is submitted.
onresetTriggered when a form is reset.
onfocusTriggered when an element receives focus.
onblurTriggered when an element loses focus.
onselectTriggered when text within an input or textarea is selected.
oninvalidTriggered when a form field fails validation.

Window / Document Events

Event AttributeDescription
onloadTriggered when the page or element is fully loaded.
onunloadTriggered when the page is closed or refreshed.
onresizeTriggered when the browser window is resized.
onscrollTriggered when the user scrolls an element or page.
onerrorTriggered when an error occurs while loading an element (like an image).

Drag & Drop Events

Event AttributeDescription
ondragTriggered while an element is being dragged.
ondragstartTriggered when drag starts.
ondragendTriggered when drag ends.
ondragenterTriggered when dragged element enters a valid drop target.
ondragleaveTriggered when dragged element leaves a drop target.
ondragoverTriggered when dragged element is over a drop target.
ondropTriggered when dragged element is dropped.

Clipboard Events

Event AttributeDescription
oncopyTriggered when text or content is copied.
oncutTriggered when text or content is cut.
onpasteTriggered when text or content is pasted.

Media Events (Audio/Video)

Event AttributeDescription
onplayTriggered when media starts playing.
onpauseTriggered when media is paused.
onendedTriggered when media playback ends.
onvolumechangeTriggered when the volume changes.
ontimeupdateTriggered when the playback position changes.
onloadeddataTriggered when media data is loaded.
onprogressTriggered while downloading media data.
onerrorTriggered when media loading fails.

Animation & Transition Events

Event AttributeDescription
onanimationstartTriggered when a CSS animation starts.
onanimationendTriggered when a CSS animation ends.
onanimationiterationTriggered when a CSS animation repeats.
ontransitionendTriggered when a CSS transition finishes.

Clipboard & Input Composition Events

Event AttributeDescription
oncompositionstartTriggered when text composition (IME) starts.
oncompositionupdateTriggered when text composition is updated.
oncompositionendTriggered when text composition ends.

Touch & Pointer Events (Mobile)

Event AttributeDescription
ontouchstartTriggered when a touch point is placed on the touch surface.
ontouchmoveTriggered when a touch point moves.
ontouchendTriggered when a touch point is removed.
onpointerdownTriggered when a pointer (mouse, pen, or touch) is pressed.
onpointerupTriggered when a pointer is released.
onpointermoveTriggered when a pointer moves.

Miscellaneous Events

Event AttributeDescription
onabortTriggered when media loading is aborted.
onbeforeunloadTriggered before a document is unloaded.
onhashchangeTriggered when the URL hash changes.
onmessageTriggered when a message is received via postMessage().
onpopstateTriggered when navigating browser history.
onstorageTriggered when data in localStorage or sessionStorage changes.

Good to know

  • onchange on a text field fires when you leave the field, not while typing. For live updates, use oninput.
  • onkeypress is deprecated. Use onkeydown instead.
  • Events on touch screens: a tap also fires onclick, so you rarely need separate touch events for buttons.

Event Attributes exercises

React to a click

Make a button with the id go that says Start. When it is clicked, its text becomes Running. Use an event attribute.

Result

Check your answer to see it here.