HTML Basic Events

Beginner
⏱️ 15 min read
📚 Updated: Jul 2026
🎯 6 Examples + 6 Try It
Event reference

Introduction

HTML event attributes let you run JavaScript when users interact with your page—clicking, typing, submitting forms, playing media, and more. They are one of the first tools beginners use to make static pages feel alive.

This guide lists the major on* attributes by category, explains what each one does, and includes hands-on examples you can edit in the Try It editor.

What You’ll Learn

01

Events

What on* means.

02

Form

Submit & input.

03

Mouse

Click & hover.

04

Keyboard

Key presses.

05

Media

Audio & video.

06

Practice

Try It editor.

What Are HTML Event Attributes?

HTML event attributes are attributes you add to elements to specify JavaScript that runs when a particular event occurs—a click, key press, focus change, or media playback milestone.

They let you define interactive behavior directly in markup. For example, a button can call a function when clicked:

html
<button type="button" onclick="alert('Hello!')">Say Hi</button>

The onclick attribute runs when the user clicks the button. Every event attribute name starts with on followed by the event type. The value is JavaScript code or a function call. Explore individual attributes in the HTML Attributes reference—most on* handlers are global attributes.

💡
Beginner Tip

Events bridge HTML and JavaScript. If you have not connected scripts yet, read How to Use JavaScript in HTML first, then return here for the full event list.

Form Event Attributes

Form event attributes are used on form controls and <form> elements. They add interactivity and validation when users focus fields, change values, or submit data.

Here are commonly used form event attributes:

AttributeDescription
onblurRuns when a form element loses focus.
onchangeRuns when the value of a form element changes and the field loses focus (or immediately for select, checkboxes, and file inputs).
onfocusRuns when a form element receives focus.
oninputRuns as the user modifies the value (every keystroke in a text field).
oninvalidRuns when an input fails constraint validation.
onresetRuns when a form is reset.
onsearchRuns when the user initiates a search on an input type="search" field.
onselectRuns when the user selects text inside an input or textarea.
onsubmitRuns when a form is submitted. Return false to cancel submission.

Keyboard Event Attributes

Keyboard event attributes capture key presses and releases. Use them for shortcuts, live search, or games.

Here are commonly used keyboard event attributes:

AttributeDescription
onkeydownRuns when a key is pressed down.
onkeyupRuns when a key is released.
onkeypressLegacy—fires for character keys. Prefer onkeydown in modern code.

Mouse Event Attributes

Mouse event attributes respond to pointer movement, clicks, and scrolling. They are among the most popular for beginner interactivity.

Here are commonly used mouse event attributes:

AttributeDescription
onclickRuns when the element is clicked with the primary mouse button.
oncontextmenuRuns when the context menu (usually right-click) opens on the element.
ondblclickRuns when the element is double-clicked.
onmousedownRuns when a mouse button is pressed down on the element.
onmousemoveRuns when the pointer moves over the element.
onmouseoutRuns when the pointer leaves the element.
onmouseoverRuns when the pointer enters the element.
onmouseupRuns when a mouse button is released over the element.
ontoggleRuns when a <details> element’s open state is toggled.
onwheelRuns when the user scrolls the mouse wheel over the element.

Drag Event Attributes

Drag events fire while the user drags an element or drops it onto a target. They power custom drag-and-drop interfaces.

Here is a list of commonly used drag event attributes:

AttributeDescription
ondragstartRuns when the user starts dragging an element.
ondragRuns repeatedly while the element is being dragged.
ondragenterRuns when a dragged element enters a valid drop target.
ondragoverRuns while a dragged element is over a valid drop target.
ondragleaveRuns when a dragged element leaves a valid drop target.
ondropRuns when a dragged element is dropped on a valid target.
ondragendRuns when the drag operation ends.

Clipboard Event Attributes

Clipboard events relate to copy, cut, and paste operations. Use them to sanitize pasted content or track clipboard actions.

Here are commonly used clipboard event attributes:

AttributeDescription
oncopyRuns when the user copies content.
oncutRuns when the user cuts content.
onpasteRuns when the user pastes content.

Media Event Attributes

Media event attributes apply to <audio> and <video> elements (and related resources). They let you react to loading, playback, pausing, and errors.

AttributeDescription
onabortRuns when media loading is aborted.
oncanplayRuns when media can start playing.
oncanplaythroughRuns when media can play through to the end without buffering.
oncuechangeRuns when active cues change on a <track> element linked to media.
ondurationchangeRuns when the media duration changes.
onemptiedRuns when media is emptied (source reset or removed).
onendedRuns when playback reaches the end.
onerrorRuns when an error occurs during loading or playback.
onloadeddataRuns when media data is loaded and ready to play.
onloadedmetadataRuns when media metadata (duration, dimensions) is loaded.
onloadstartRuns when loading of media begins.
onpauseRuns when playback is paused.
onplayRuns when playback starts.
onplayingRuns when playback is active after being paused or delayed.
onprogressRuns periodically while a resource is downloading.
onratechangeRuns when the playback rate changes.
onseekedRuns when a seek operation completes.
onseekingRuns when a seek operation begins.
onstalledRuns when media loading is interrupted or stalled.
onsuspendRuns when media loading is intentionally suspended.
ontimeupdateRuns when the current playback position changes.
onvolumechangeRuns when volume or mute state changes.
onwaitingRuns when playback waits for more data.

Window Event Attributes

Window event attributes are often placed on <body> or registered on the window object in JavaScript. They relate to page load, navigation, connectivity, and browser window changes.

AttributeDescription
onafterprintRuns after the print dialog closes.
onbeforeprintRuns before print or print preview.
onbeforeunloadRuns when the user attempts to leave the page; can show a confirmation dialog.
onhashchangeRuns when the URL fragment (#...) changes.
onloadRuns when the page or an element finishes loading.
onmessageRuns when a message is received from another window or iframe.
onofflineRuns when the browser goes offline.
ononlineRuns when the browser comes back online.
onpagehideRuns when the page is about to be hidden or unloaded.
onpageshowRuns when the page is shown (including back/forward navigation).
onpopstateRuns when the user navigates through browser history.
onresizeRuns when the browser window is resized.
onunloadRuns when the page is about to unload (largely replaced by pagehide).

Best Practices

✅ Do

  • Use event attributes to learn how clicks and forms work
  • Move to addEventListener as projects grow
  • Return false from onsubmit to block invalid forms
  • Use semantic elements (<button>, <form>) with events
  • Link to individual attribute pages for deeper reference

❌ Don’t

  • Put large scripts inside every onclick attribute
  • Rely on inline events for security-sensitive logic alone
  • Use onkeypress for new projects—prefer onkeydown
  • Depend on onunload for critical save logic (unreliable on mobile)
  • Forget keyboard and screen-reader users when using mouse-only events

Modern alternative in a script block:

js
document.querySelector('#myBtn').addEventListener('click', function () {
  alert('Clicked with addEventListener!');
});

Examples Gallery

Six examples covering the most common beginner events. Each includes View Output and Try It Yourself.

Example 1 — onclick

html
<button type="button" onclick="document.getElementById('msg').textContent='Button clicked!'">
  Click Me
</button>
<p id="msg">Waiting...</p>
Try It Yourself

Example 2 — onmouseover & onmouseout

html
<div onmouseover="this.style.background='#dbeafe'"
     onmouseout="this.style.background=''">
  Hover over me
</div>
Try It Yourself

Example 3 — onchange

html
<select onchange="document.getElementById('out').textContent='You chose: '+this.value">
  <option value="Red">Red</option>
  <option value="Blue">Blue</option>
</select>
<p id="out"></p>
Try It Yourself

Example 4 — onsubmit

html
<form onsubmit="return nameOK()">
  <input type="text" id="name" required>
  <button type="submit">Submit</button>
</form>
<script>
  function nameOK() {
    if (document.getElementById('name').value.length < 2) return false;
    return false;
  }
</script>
Try It Yourself

Example 5 — onkeydown

html
<input type="text" onkeydown="showKey(event)">
<p id="key">Press a key...</p>
Try It Yourself

Example 6 — onfocus & onblur

html
<input type="email"
       onfocus="this.style.borderColor='#2563eb'"
       onblur="this.style.borderColor='#cbd5e1'">
Try It Yourself

Universal Browser Support

Standard HTML event attributes (onclick, onchange, onsubmit, keyboard and mouse events) are supported in every modern browser. Media and drag events work wherever audio, video, and drag-and-drop APIs are available.

Baseline · Since HTML4

HTML event attributes

Core on* handlers work in Chrome, Firefox, Safari, Edge, and mobile browsers without polyfills.

100% Core event support
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
Common on* attributes Universal

Bottom line: Event attributes are part of the HTML standard—use them confidently while learning.

Conclusion

HTML event attributes are your entry point to interactive web pages. From onclick and onchange to media and window events, each on* name maps to a moment in the browser you can respond to with JavaScript.

Bookmark this page as a reference, practice with the Try It examples, then graduate to addEventListener and external scripts as your skills grow.

Key Takeaways

📝02

Form events

focus, change, submit.

Forms
🖱03

Mouse

click & hover.

Pointer
04

Keyboard

keydown & keyup.

Input
🎧05

Media

play, pause, ended.

AV
▶️06

Try It

Hands-on demos.

Practice

❓ Frequently Asked Questions

Event attributes are on* properties on HTML elements—onclick, onchange, onsubmit, and many more. When the matching browser event fires, the JavaScript code in the attribute runs. They provide a quick way to add interactivity without separate script files.
onclick is an HTML attribute with inline JavaScript. addEventListener is a JavaScript API that attaches handlers from a script block or external file. addEventListener is preferred in real projects because it keeps behavior separate from markup and supports multiple handlers.
Most global event attributes work on almost any element. Some events are meaningful only on certain tags—onsubmit on forms, onplay on video, ontoggle on details. Browsers ignore meaningless combinations, but use events on appropriate elements for clarity.
onclick is the most common—users click buttons and links constantly. onchange is next for forms and selects. onmouseover and onmouseout introduce hover effects. Start with these before exploring keyboard, drag, or media events.
No. If JavaScript is disabled, on* handlers never run. Critical actions like form submission should still work with native HTML (required, type=email) and server-side validation—not only client-side event scripts.
Dozens. This guide groups them into form, keyboard, mouse, drag, clipboard, media, and window categories. Roughly 70+ on* attributes exist in modern HTML; you only need a handful for most beginner pages.
Did you know?

The DOM Level 0 event model (inline onclick attributes) dates back to the earliest browsers. The modern addEventListener API arrived in the early 2000s—but HTML event attributes remain the fastest way to see cause and effect when you are learning.

Make a page respond to clicks

Open the Try It editor and wire up your first onclick handler.

Open Try It editor →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful