References

Beginner-friendly references for web development, with live, editable examples.

The HTML oncontextmenu event

Event All modern browsers Updated
Quick answer

The HTML oncontextmenu attribute runs JavaScript when the user requests a context menu (usually a right-click). It is an inline handler for the contextmenu event; in modern code prefer addEventListener('contextmenu', …).

Overview

The oncontextmenu event attribute runs JavaScript when the context menu is requested, e.g. on right-click. In JavaScript the event itself is named contextmenu — drop the on prefix when you call addEventListener.

It is one of the mouse events. Its handler receives a MouseEvent with details such as the pointer coordinates (clientX/clientY), which button was used, and which modifier keys were held. For input that also covers touch and pen with one code path, the modern pointer events are the recommended replacement.

You can wire this up with the inline oncontextmenu HTML attribute, but the modern, recommended approach is element.addEventListener('contextmenu', handler) in JavaScript. That keeps behavior out of your markup, lets you attach several handlers to the same event, and makes them easy to remove. The inline attribute is fine for quick demos.

Syntax

<element oncontextmenu="handler()">…</element>

element.addEventListener('contextmenu', handler);

Example

Live example
<div oncontextmenu="event.preventDefault(); this.textContent='Custom menu!'" style="padding:10px;background:#eef5ff;border-radius:6px;">Right-click me</div>

Best practices

  • Prefer element.addEventListener('contextmenu', handler) over the inline oncontextmenu attribute — it separates behavior from markup and allows multiple handlers.
  • Build interactivity on real <button> or link elements so it also works with the keyboard — not on mouse events alone.
  • Consider the unified pointer events to handle mouse, touch and pen together.
  • Read coordinates and the pressed button from the MouseEvent the handler receives.

Frequently asked questions

What is the oncontextmenu event?
It runs JavaScript when the context menu is requested, e.g. on right-click. In JavaScript the event is named contextmenu.
Does this event work on touch screens?
Mouse events have limited support on touch devices. For input that works across mouse, touch and pen, use the pointer events instead.
How do I get the mouse position?
Read event.clientX and event.clientY (viewport-relative) from the MouseEvent passed to the handler.
Should I use the oncontextmenu attribute or addEventListener?
Prefer addEventListener('contextmenu', …) in JavaScript. The inline oncontextmenu attribute works but mixes behavior into the markup and allows only one handler per element.