HTML oncontextmenu Event Attribute
Description
The oncontextmenu HTML event attribute specifies a script to be run when the user tries to open the context menu of an element, usually by right-clicking it, by pressing the context menu key, or by a long press on touch screens. It is supported in all browsers and can be used on any element.
The oncontextmenu attribute takes a single value, which is the JavaScript code to be executed when the event is fired. The code can be either a function name or a code block.
For example, the following code will prevent the context menu from being displayed when the user right-clicks on a div element:
<div oncontextmenu="event.preventDefault()">
This is a div element.
</div>
The following code will display a custom message when the user right-clicks on an <img> element:
<img src="photo.jpg" alt="Photo" oncontextmenu="alert('Hello, world!')">
The oncontextmenu attribute can be used on any HTML element. It is often used to provide custom functionality for right-clicking on elements, such as displaying custom menus or preventing the default context menu from being displayed.
Here are some examples of how the oncontextmenu attribute can be used:
- Display a custom context menu for an image element, allowing the user to save the image, copy the image URL, or open the image in a new tab.
- Prevent the context menu from being displayed for a certain element, such as a login form.
- Display a warning message when the user right-clicks on a sensitive element, such as a credit card number field.
Syntax
<element oncontextmenu="script">
Values
- scriptThe name of the script to use when the event has been triggered.
Example
Browser Support
The following information will show you the current browser support for the HTML oncontextmenu event attribute. Hover over a browser icon to see the version that first introduced support for this HTML event attribute.
Desktop





Tablets & Mobile





