HTML oncontextmenu Attribute

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

Introduction

The oncontextmenu attribute is an inline event handler that runs JavaScript when the contextmenu event fires. That usually happens when the user right-clicks an element (or long-presses on touch devices) — the gesture that opens a browser context menu. Developers use it to run custom logic, show a custom menu, or call event.preventDefault() to block the default menu. The contextmenu event bubbles, so you can listen on a parent. For production sites, prefer addEventListener("contextmenu", …) and always consider accessibility when replacing the browser menu.

What You’ll Learn

01

Event handler

Inline JS.

02

contextmenu

Right-click.

03

preventDefault

Block default.

04

vs onclick

Right vs left.

05

addEventListener

Preferred way.

06

Custom menu

Build your own.

Purpose of oncontextmenu Attribute

The primary purpose of oncontextmenu is to react when the user opens a context menu on an element — typically by right-clicking. Common uses include showing a custom menu with actions like “Copy link” or “Delete item”, disabling the default menu on images, or running validation before allowing browser actions. Pair it with event.preventDefault() when you replace the built-in menu with your own UI.

Do not confuse oncontextmenu with onclick. A right-click may also fire other events, but contextmenu is specifically tied to the menu gesture. Blocking the default menu without offering alternatives hurts usability — only customize when it clearly helps the user.

💡
Call preventDefault() for custom menus

To hide the browser’s context menu, call event.preventDefault() inside your handler, then display your custom menu at event.clientX and event.clientY.

📝 Syntax

Set oncontextmenu on any element or assign element.oncontextmenu:

oncontextmenu.html
<script>

  function handleContextMenu(event) {

    event.preventDefault();

    document.getElementById("status").textContent = "Custom menu action!";

  }

</script>



<div id="box" oncontextmenu="handleContextMenu(event)">

  Right-click me

</div>

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

Syntax Rules

  • Value is JavaScript code executed when the context menu gesture occurs.
  • Pass event to the handler so you can call event.preventDefault().
  • Works on almost any element: div, img, button, p, etc.
  • JavaScript: element.oncontextmenu = function(e) { … }.
  • Modern alternative: element.addEventListener("contextmenu", handler).
  • The contextmenu event bubbles — you can delegate on a parent container.

💎 Values

The oncontextmenu attribute accepts a string of JavaScript code:

  • oncontextmenu="handleMenu(event)" — Call a function with the event object.
  • oncontextmenu="event.preventDefault()" — Block the browser menu (use carefully).
  • JavaScript: box.oncontextmenu = (e) => { … } assigns the handler.
oncontextmenu-js.html
const box = document.getElementById("box");

box.addEventListener("contextmenu", (event) => {

  event.preventDefault();

  showCustomMenu(event.clientX, event.clientY);

});

// Dynamic assignment

document.getElementById("photo").oncontextmenu = function (e) {

  e.preventDefault();

  console.log("Image context menu blocked");

};

⚡ Quick Reference

EventWhen it firesHandler
contextmenuRight-click / long-pressoncontextmenu
clickPrimary clickonclick
preventDefault()Block browser menuIn handler
clientX / clientYPointer positionPosition custom menu
Touch devicesLong-press gestureAlso fires contextmenu
Bubbles?contextmenu yesDelegate on parent

Applicable Elements

TargetSupported?Notes
<div>, <span>YesCommon for custom menu zones
<img>YesOften used to protect or customize image menus
<button>YesRight-click on buttons
<a href>YesCustom link actions on right-click
<input>, <textarea>YesBrowser may still show text-editing menu items

oncontextmenu vs onclick vs onmousedown

HandlerWhen it firesTypical use
onmousedownAny mouse button pressedDrag, press feedback
onclickPrimary click (left button)Buttons, toggles, links
oncontextmenuRight-click / menu gestureCustom context menus

Examples Gallery

Inline oncontextmenu with preventDefault, addEventListener on an image, and a simple custom context menu.

👀 Live Preview

Right-click the box below (browser menu is blocked for this demo):

Right-click me

Try a right-click on the box.

Example — Inline oncontextmenu

Run a function when the user right-clicks, and block the default menu:

inline-oncontextmenu.html
<button type="button" oncontextmenu="handleMenu(event)">

  Right-click me

</button>



<script>

  function handleMenu(event) {

    event.preventDefault();

    document.getElementById("msg").textContent = "Custom context action!";

  }

</script>
Try It Yourself

How It Works

The browser fires contextmenu before showing the default menu. Your handler can cancel it and run custom logic instead.

Dynamic Values with JavaScript

Attach the handler with addEventListener on an image:

dynamic-oncontextmenu.html
<script>

  document.getElementById("photo").addEventListener("contextmenu", function (event) {

    event.preventDefault();

    showCustomMenu(event.clientX, event.clientY);

  });



  // Or property form:

  document.getElementById("photo").oncontextmenu = function (e) { e.preventDefault(); };

</script>
Try It Yourself

How It Works

Register the listener once at page load. On right-click, prevent the default menu and show your UI at the pointer coordinates.

Example — Simple custom menu

Build a minimal menu div that appears on right-click:

custom-context-menu.html
area.addEventListener("contextmenu", (e) => {

  e.preventDefault();

  menu.style.left = e.clientX + "px";

  menu.style.top = e.clientY + "px";

  menu.hidden = false;

});



document.addEventListener("click", () => { menu.hidden = true; });
Try It Yourself

How It Works

preventDefault() blocks the browser menu. Position your menu with CSS left / top from the event coordinates.

♿ Accessibility

  • Do not block without alternatives — If you call preventDefault(), provide a custom menu with the same essential actions (copy, open link, etc.).
  • Keyboard access — Custom menus need keyboard navigation (arrow keys, Escape to close) and focus management.
  • Screen readers — Use role="menu", role="menuitem", and visible focus on custom menu items.
  • Avoid alert() on contextmenu — Show a positioned menu or status text instead of modal alerts.
  • Touch users — Long-press triggers contextmenu on mobile; test custom menus on touch devices.

🧠 How oncontextmenu Works

1

User right-clicks

Or long-press on touch.

Gesture
2

contextmenu fires

Before default menu shows.

Event
3

Handler runs

Optional preventDefault().

oncontextmenu
=

Custom menu or action

Show UI at cursor.

Browser Support

The contextmenu event and oncontextmenu handler are supported in all modern browsers — Chrome, Firefox, Safari, and Edge. Long-press on mobile also triggers the event on supported elements.

DOM Events · Fully supported

Universal oncontextmenu support

All major browsers fire the underlying event and honor the oncontextmenu 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
oncontextmenu attribute 99% supported

Bottom line: Universal support. Test custom menus on desktop (right-click) and mobile (long-press) before shipping.

💡 Best Practices

✅ Do

  • Use addEventListener on the element — Clearer than inline oncontextmenu.
  • Call preventDefault() only when needed — Let the browser menu work unless you show a real custom replacement.
  • Position with clientX / clientY — Place custom menus at the pointer using fixed or absolute positioning.
  • Close on outside click — Hide the custom menu when the user clicks elsewhere or presses Escape.
  • Keep menus short — Mirror familiar browser actions; avoid overwhelming users with too many options.

❌ Don’t

  • Do not disable right-click globally — Site-wide blocking frustrates users and hurts accessibility.

Conclusion

The oncontextmenu attribute runs JavaScript when a user opens a context menu on an element and the contextmenu event fires. Use it with event.preventDefault() to show custom menus or run targeted actions on right-click.

Prefer addEventListener("contextmenu", …), provide accessible alternatives when blocking the default menu, and test on both desktop and touch devices.

Key Takeaways

Knowledge Unlocked

Five truths every developer should know about oncontextmenu

Bookmark these before wiring your next event handler.

5
Core concepts
🌐 02

Many elements

div, img, button.

Scope
🔄 03

preventDefault

Block default menu.

Pattern
📝 04

addEventListener

Preferred.

Modern
05

Custom menu

At clientX/Y.

Note

❓ Frequently Asked Questions

It runs JavaScript when the contextmenu event fires — usually on right-click or long-press.
Almost any element: div, img, button, p, and more.
Call event.preventDefault(), then show your menu at event.clientX and event.clientY.
onclick is a primary click. oncontextmenu is the right-click / menu gesture.
Prefer element.addEventListener("contextmenu", …). Inline oncontextmenu works for simple demos.
Only if you provide an equivalent custom menu with keyboard support. Avoid blocking without a usable alternative.

Customize right-click menus

Practice inline oncontextmenu, preventDefault, and custom menus in the Try It editor.

Try oncontextmenu 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