HTML oncontextmenu Event Attribute
Description
The oncontextmenu HTML event attribute specifies a script to be run when the user right-clicks on an element. It is currently only supported in Firefox, but the oncontextmenu event itself is supported in all browsers.
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 image element:
<image oncontextmenu="alert('Hello, world!')">
This is an image element.
</image>
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.
- Implement custom drag-and-drop functionality by listening for the
contextmenuevent and starting a drag operation when the user right-clicks and drags the element.
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.
This event attribute is supported by all modern browsers.
Desktop
Tablets & Mobile
Last updated by CSSPortal on: 14th October 2023
