JavaScript - Hide the context menu
A simple code example to hide the context menu when right-clicked using JavaScript.
The HTML specifies the <div> tag with the id "target" as the area to right-click on.
<div id="target">The context menu will not be displayed in this area.</div>
The CSS sets the size for the click target. Specifies text properties to display the number of clicks.
Sets the hover cursor to a pointer with "cursor: pointer".
#target {
display: flex;
align-items: center;
justify-content: center;
padding: 10px;
color: white;
width: 250px;
height: 250px;
border-radius: 50%;
text-align: center;
cursor: pointer;
user-select: none;
transition: 1s;
font-size: 20px;
background: #0000cd;
}
Selects the element to disable the context menu with querySelector()
and implements the right click event with addEventListener()
.
Specifies preventDefault()
so that the browser does not open the default context menu.
// Implement right click event
document.querySelector('#target').addEventListener('contextmenu', () => {
// Don't display context menu
event.preventDefault();
});