HTML Basic Events

Beginner
12 min read
Updated: Nov 2026
6 examples
onclick / onchange

Definition and Usage

HTML event attributes are on* attributes you put on elements so the page can react when something happens—a click, a form change, a key press, or focus moving into a field.

What does an event attribute do?

The attribute name names the event (onclick, onchange). The value is JavaScript that runs when that event fires. That is how a static HTML page starts feeling interactive.

Where do beginners start?

Learn onclick on buttons, onchange / onsubmit on forms, mouse enter/leave for hover demos, and onkeydown / onfocus for inputs. If you have not linked scripts yet, see JavaScript in HTML first.

Inline attributes vs script listeners

Inline on* attributes are great for learning and tiny examples. As pages grow, prefer addEventListener in a <script> so markup stays readable and you can attach more than one handler per event.

Name pattern.

Almost every event attribute starts with on + the event type: onclick, onload, oninput.

Needs JavaScript.

If scripting is blocked or disabled, event attributes do nothing. Keep critical form behavior in HTML + the server too.

Attribute pages.

Deep per-attribute notes live under HTML Attributes (many on* names are global).

HTML Syntax

Put the handler on the element that should react:

HTML
<button type="button"
  onclick="document.getElementById('msg').textContent = 'Clicked!'">
  Click Me
</button>
<p id="msg">Waiting…</p>

Modern alternative (same idea, separate script):

JS
document.querySelector("#myBtn").addEventListener("click", function () {
  document.getElementById("msg").textContent = "Clicked!";
});

Core HTML Concepts

Events you will use most often on HTML pages:

AttributeFires whenTypical HTML use
onclickPrimary click<button>, links, cards
onchangeValue committedselect, checkboxes, text after blur
onsubmitForm is submitted<form> (return false to cancel)
onmouseover / onmouseoutPointer enters / leavesHover highlight demos
onkeydownKey pressedInputs, shortcuts
onfocus / onblurFocus gained / lostForm fields

Event groups (quick map)

GroupExamples
Formoninput, onchange, onsubmit, onfocus, onblur
Mouseonclick, ondblclick, onmousedown, onmouseover
Keyboardonkeydown, onkeyup (prefer these over legacy onkeypress)
Clipboardoncopy, oncut, onpaste
Mediaonplay, onpause, onended on audio/video
Window / bodyonload, onresize, onbeforeunload

Inline attribute vs addEventListener

onclick="…"addEventListener
Where it livesInside HTML markupIn a script file or block
Multiple handlersOne attribute overwrites itselfMany listeners allowed
Best forLearning, tiny demosApps and maintainable pages

How to Add Events in HTML

A practical workflow:

  1. Pick the element that should react (button, input, form, …).
  2. Choose the matching on* attribute for the user action.
  3. Write a short JavaScript expression or call a named function.
  4. Update the page (text, styles, show/hide) from that handler.
  5. When the demo grows, move the same logic into addEventListener.
GoalHTML pattern
Button feedback<button onclick="…">
Select choice<select onchange="…">
Validate before send<form onsubmit="return check();">
Highlight on hoveronmouseover / onmouseout (or CSS :hover)

Live Preview

Click the button—an onclick-style handler updates the message (wired with addEventListener under the hood).

Same idea as onclick on a button in HTML.

Message

Waiting for a click…

HTML Examples

Six beginner patterns: click, hover, change, submit, keydown, and focus/blur.

Example 1 — onclick

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

How It Works

  1. onclick listens for a primary click on the button.
  2. getElementById finds the paragraph to update.
  3. textContent replaces the waiting message.
  4. type="button" avoids accidental form submit.

Example 2 — onmouseover & onmouseout

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

How It Works

  1. onmouseover runs when the pointer enters.
  2. onmouseout runs when the pointer leaves.
  3. this refers to the hovered element.
  4. CSS :hover is often cleaner for pure style changes.

Example 3 — onchange

HTML
<label for="color">Pick a color:</label>
<select id="color"
  onchange="document.getElementById('out').textContent = 'You chose: ' + this.value">
  <option value="">-- choose --</option>
  <option value="Red">Red</option>
  <option value="Green">Green</option>
  <option value="Blue">Blue</option>
</select>
<p id="out">No selection yet.</p>
Try It Yourself

How It Works

  1. onchange fires when the selected option changes.
  2. this.value is the chosen option value.
  3. label for keeps the control accessible.
  4. oninput is better when you need every keystroke in a text field.

Example 4 — onsubmit

HTML
<form onsubmit="return checkName()">
  <label>Name: <input type="text" id="name" required></label>
  <button type="submit">Submit</button>
</form>
<p id="status"></p>
<script>
  function checkName() {
    var name = document.getElementById("name").value.trim();
    if (name.length < 2) {
      document.getElementById("status").textContent = "Name must be at least 2 characters.";
      return false;
    }
    document.getElementById("status").textContent = "Form would submit: " + name;
    return false;
  }
</script>
Try It Yourself

How It Works

  1. onsubmit runs before the browser sends the form.
  2. return false cancels navigation in this demo.
  3. required still helps with empty fields.
  4. Always validate again on the server in real apps.

Example 5 — onkeydown

HTML
<label>Type here:
  <input type="text" onkeydown="showKey(event)">
</label>
<p id="key">Press a key…</p>
<script>
  function showKey(e) {
    document.getElementById("key").textContent =
      "Last key: " + e.key + " (code: " + e.code + ")";
  }
</script>
Try It Yourself

How It Works

  1. onkeydown fires as soon as a key goes down.
  2. event.key is the character or key name.
  3. event.code is the physical key id.
  4. Prefer onkeydown over legacy onkeypress.

Example 6 — onfocus & onblur

HTML
<label>Email:
  <input type="email"
       onfocus="this.style.borderColor='#2563eb'"
    onblur="this.style.borderColor='#cbd5e1'"
    placeholder="[email protected]">
</label>
Try It Yourself

How It Works

  1. onfocus runs when the field becomes active.
  2. onblur runs when focus leaves.
  3. Border color gives visual feedback.
  4. CSS :focus can replace this for simple styling.

Edge Cases & Pitfalls

Most beginner event bugs come from mixing markup with too much script or forgetting accessibility.

size

Huge code inside onclick

Long inline scripts are hard to read and debug. Call a named function or use addEventListener.

a11y

Mouse-only handlers

Keyboard users may never fire onmouseover. Prefer buttons/links and CSS :focus-visible where possible.

form

Forgetting return false

Invalid onsubmit checks that do not return false (or call preventDefault) still navigate away.

csp

Content Security Policy

Many hosts block inline event attributes. External scripts with listeners are safer and more portable.

legacy

onkeypress

Deprecated for new work. Use onkeydown / onkeyup instead.

css

Hover via JS only

For color/background changes, CSS :hover is usually simpler than onmouseover.

Browser Support

HTML event attributes and the DOM Event API are Baseline web platform features. Common handlers like click, change, submit, keydown, and focus work in all modern browsers.

✓ Baseline · Widely available

HTML events

on* attributes and script listeners work across current browsers worldwide.

100% basic events
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
HTML basic events Universal

Bottom line: Start with onclick, onchange, and onsubmit in HTML; graduate to addEventListener for real projects.

Key Takeaways

  • on* attributes run JavaScript when page events fire.
  • Learn with onclick / onchange / onsubmit, then expand.
  • addEventListener scales better than inline attributes.
  • Scripts primer: /html/javascript-in-html; forms: /html/form.

One line: Attach an on* attribute (or a script listener) so HTML elements can respond to clicks, form changes, and keys.

Frequently Asked Questions

They are on* attributes in HTML markup—onclick, onchange, onsubmit, and similar—that run JavaScript when the user or browser triggers that event on an element.
onclick attributes are fine for learning and tiny demos. For real projects, prefer addEventListener in a script so markup stays clean, multiple handlers can share one event, and Content Security Policy is easier to satisfy.
Start with onclick, onchange, onsubmit, onmouseover/onmouseout, onkeydown, and onfocus/onblur. Those cover buttons, forms, hover, typing, and focus.
No. If scripting is disabled, on* handlers never run. Keep forms usable with native HTML (required, proper types) and server checks.
Many global events work on most elements, but some only make sense on specific tags—onsubmit on form, onplay on video, ontoggle on details.
In onsubmit, return false (or call event.preventDefault() in a script listener) when validation fails.

Practice in the editor

Open a Try It demo and wire onclick, onchange, or onsubmit yourself.

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.

8 people found this page helpful