oncontextmenu

The oncontextmenu event is triggered when a user right-clicks an HTML element to open the context menu. For more details, refer to Mouse Events.

oncontextmenu event

The oncontextmenu event attribute activates when the user right-clicks on an element, opening the context menu. This event allows for customization of the menu or execution of specific actions. To use it, add the attribute to the element and define the <script> to execute when the event is triggered.

Syntax

In HTML

index.html
<element oncontextmenu="myScript">

In JS

script.js
object.oncontextmenu = function(){myScript};

In JavaScript, the addEventListener() function is used.

script.js
object.addEventListener("contextmenu", myScript);

Example

::event-oncontextmenu ::
index.html
<!DOCTYPE html>
<html>
<body>
<h1>HTML DOM Events</h1>
<h2>The contextmenu Event</h2>

<div style="border:1px solid black;text-align:center">
<p>Right-click in this box!</p>
<p>Context menu will show.</p>
</div>
<br>
<div id="myDiv" style="border:1px solid black;text-align:center">
<p>Right-click in this box!</p>
<p>Context menu is disabled.</p>
</div>

<script>
const div = document.getElementById("myDiv");
div.addEventListener("contextmenu", (e) => {e.preventDefault()});
</script>

</body>
</html>

Values

Conclusion

The oncontextmenu event is triggered when a user right-clicks on an element, allowing for customization of the context menu or the execution of specific actions. It enhances interactivity by enabling developers to create custom right-click menus. This event is useful for offering alternative options to users.