HTML onclick Attribute

Beginner
⏱️ 5 min read
📚 Updated: Jun 2026
🎯 3 Examples
Events & Handlers

Introduction

The onclick attribute is an inline event handler that runs JavaScript when the click event fires. That happens when the user clicks an element with a mouse, trackpad, or touch tap—or when they activate a focusable control with the keyboard (Enter or Space on a <button>). It is one of the most common ways to add interactivity: toggling panels, submitting actions, updating counters, or showing messages. The click event bubbles, so you can handle many buttons with one listener on a parent. For production sites, prefer addEventListener("click", …) over inline handlers.

What You’ll Learn

01

Event handler

Inline JS.

02

click event

Mouse / tap.

03

Many elements

button, div, a.

04

vs ondblclick

Single vs double.

05

addEventListener

Preferred way.

06

.onclick

Property API.

Purpose of onclick Attribute

The primary purpose of onclick is to define what happens when a user clicks an element. Common uses include running a function when a button is pressed, toggling a menu open or closed, incrementing a counter, copying text to the clipboard, or showing a confirmation message. It connects user pointer actions directly to JavaScript behavior without a full page reload.

Do not confuse onclick with onchange. Click responds to pointer activation; change responds when a form value is committed. For navigation to another page, prefer <a href> over onclick="location.href=…" so links work without JavaScript and are easier for users and search engines.

💡
Prefer addEventListener on the element

Production code should use button.addEventListener("click", handler). Inline onclick on <button> works for tutorials but mixes markup and behavior.

📝 Syntax

Set onclick on any element or assign element.onclick:

onclick.html
<script>

  function handleClick() {

    document.getElementById("status").textContent = "Button clicked!";

  }

</script>



<button type="button" onclick="handleClick()">Click me</button>

<p id="status"></p>

Syntax Rules

  • Value is JavaScript code executed when the element receives a click.
  • Works on almost any element: button, a, div, input, img, etc.
  • Use type="button" on buttons inside forms to avoid accidental submit.
  • JavaScript: element.onclick = function() { … }.
  • Modern alternative: element.addEventListener("click", handler).
  • The click event bubbles — you can delegate on a parent container.

💎 Values

The onclick attribute accepts a string of JavaScript code:

  • onclick="handleClick()" — Call a named function.
  • onclick="this.classList.toggle('active')" — Inline statement on the element.
  • JavaScript: btn.onclick = () => { … } assigns the handler.
onclick-js.html
const btn = document.getElementById("save");

btn.addEventListener("click", () => {

  console.log("Save clicked");

});

// Dynamic assignment

document.getElementById("toggle").onclick = function () {

  this.classList.toggle("open");

};

⚡ Quick Reference

EventWhen it firesHandler
clickPrimary pointer activationonclick
dblclickDouble clickondblclick
mousedownMouse button pressed downonmousedown
Keyboard on buttonEnter / SpaceAlso fires click
Form value commitAfter edit + bluronchange
Bubbles?click yesDelegate on parent

Applicable Elements

TargetSupported?Notes
<button>YesPrimary and recommended use
<a href>YesPrefer href for navigation
<div>, <span>YesNeeds keyboard + ARIA for a11y
<input type="button">YesForm button input
<img>YesImage map or custom UI only

onclick vs ondblclick vs onmousedown

HandlerWhen it firesTypical use
onmousedownButton pressed downDrag start, press feedback
onclickFull click (down + up)Buttons, toggles, actions
ondblclickTwo clicks in quick successionZoom, edit on double-click

Examples Gallery

Inline onclick on a button, addEventListener click, and event delegation on a parent container.

👀 Live Preview

Click the button to update the message:

Waiting for a click…

Example — Inline onclick on button

Run a function when the user clicks a button:

inline-onclick.html
<button type="button" onclick="showMessage()">Click me</button>

<p id="msg"></p>



<script>

  function showMessage() {

    document.getElementById("msg").textContent = "Button clicked!";

  }

</script>
Try It Yourself

How It Works

The browser fires click on the button when activated. The inline onclick attribute calls your function at that moment.

Dynamic Values with JavaScript

Attach the handler with addEventListener:

dynamic-onclick.html
<script>

  document.getElementById("save").addEventListener("click", function () {

    console.log("Save clicked");

  });



  // Or property form:

  document.getElementById("toggle").onclick = function () { /* … */ };

</script>
Try It Yourself

How It Works

Register the listener once at page load. Each click runs your handler with this pointing at the element.

Example — Event delegation

Because click bubbles, one listener on a parent can handle many buttons:

click-delegation.html
document.getElementById("toolbar").addEventListener("click", (e) => {

  if (e.target.matches("button[data-action]")) {

    console.log("Action:", e.target.dataset.action);

  }

});
Try It Yourself

How It Works

The click event travels up the DOM. The parent checks event.target to see which child was clicked, avoiding a separate handler per button.

♿ Accessibility

  • Use semantic elements — Prefer <button type="button"> over <div onclick> so keyboard and screen reader users can activate controls.
  • Keyboard activation — Native buttons fire click on Enter and Space. Custom clickable divs need tabindex="0" and key handlers.
  • Avoid alert() on click — Inline status text or visible UI updates are more accessible than modal alerts.
  • Navigation — Use <a href> for links instead of onclick="location.href=…" so users can open in new tabs and navigate without JS.
  • Focus visible — Do not remove focus outlines on clickable elements; users need to see which control is active.

🧠 How onclick Works

1

User clicks element

Mouse, tap, or keyboard activation.

Pointer
2

Browser dispatches click

Full press-and-release on target.

Event
3

click event fires

Handler runs on element.

onclick
=

Run your action

Toggle, save, navigate.

Browser Support

The click event and onclick handler are supported in all modern browsers — Chrome, Firefox, Safari, and Edge. Behavior is consistent across elements and input devices.

DOM Events · Fully supported

Universal onclick support

All major browsers fire the underlying event and honor the onclick handler attribute.

99% Browser support
Google Chrome Fully supported
Full support
Mozilla Firefox Fully supported
Full support
Apple Safari Fully supported
Full support
Microsoft Edge Fully supported
Full support
Internet Explorer IE 9+ supported
Full support
Opera Fully supported
Full support
onclick attribute 99% supported

Bottom line: Universal support on all elements. Test with mouse, touch, and keyboard (Tab + Enter/Space on buttons).

💡 Best Practices

✅ Do

  • Use addEventListener on the element — Clearer than inline onclick.
  • Use semantic buttons — <button type="button"> instead of clickable divs when possible.
  • Set type on buttons in forms — Avoid accidental form submit with type="submit" defaults.
  • Keep handlers fast — Long tasks should use async patterns so the UI stays responsive.
  • Delegate when useful — click bubbles — one listener on a list container can handle many items.

❌ Don’t

  • Do not use onclick for navigation — Prefer real links with href for better UX and SEO.

Conclusion

The onclick attribute runs JavaScript when a user clicks an element and the click event fires. Use it to add interactivity — toggles, counters, custom actions — on buttons and other elements.

Prefer addEventListener("click", …), use semantic <button> elements, and remember that click bubbles for event delegation on parent containers.

Key Takeaways

Knowledge Unlocked

Five truths every developer should know about onclick

Bookmark these before wiring your next event handler.

5
Core concepts
🌐 02

Many elements

button, div, a.

Scope
🔄 03

vs ondblclick

Single vs double.

Pattern
📝 04

addEventListener

Preferred.

Modern
05

Bubbles

Delegate clicks.

Note

❓ Frequently Asked Questions

It runs JavaScript when the click event fires — when the user clicks or activates an element.
Almost any element: button, a, div, input, and more. Prefer semantic interactive elements.
onclick is one inline handler in HTML. addEventListener("click", …) is the modern JS API with multiple handlers and cleaner separation.
onclick fires on a single click. ondblclick fires on a double click.
Prefer <button type="button">. Divs with onclick need extra keyboard and ARIA support to be accessible.
Yes. Use event delegation — one listener on a parent can handle clicks from many children.

Handle clicks with JavaScript

Practice inline onclick, addEventListener, and event delegation in the Try It editor.

Try onclick demo →

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.

5 people found this page helpful