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 contextmenu event 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

<!DOCTYPE html> 
<html>
<head>
<title>oncontextmenu event</title>
</head>
<body>
<div contextmenu="testmenu" oncontextmenu="testFunction()">Click on me with the right mouse button.
<menu type="context" id="testmenu">
<menuitem label="like"> </menuitem>
<menuitem label="dislike"> </menuitem>
</menu>
</div>
<script>
function testFunction () {
alert("EXAMPLE: You are invoking the context menu!");
}
</script>
</body>
</html>

Browser Support

The following table will show you the current browser support for the HTML oncontextmenu Event Attribute.

Desktop
Edge Chrome Firefox Opera Safari
YesYesYesYesYes
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
YesYesYesYesYesYes

Last updated by CSSPortal on: 14th October 2023