Sometimes, we may want to add a right-click menu to a webpage.
In this article, we’ll look at how to add a right-click menu to a webpage with JavaScript.
Listening to the contextmenu and click Events
To open a context menu on right-click, we attach an event listener to the contextmenu
event and call preventDefault
to prevent the default action in the event listener.
The default action is to open the browser’s context menu.
Then after that, we can add code to open the menu.
To close the menu when we left-click on the page, we add a click
event listener and then set the styles to close the menu.
To do this, we write the following HTML to create a context menu:
<ul id="ctxMenu">
<li>Save</li>
<li>Save As</li>
<li>Open</li>
</ul>
Then we add some CSS styles by writing:
#ctxMenu {
border: 1px solid black;
padding: 10px;
list-style-type: none;
display: none;
position: absolute;
width: 200px;
}
We add a border and make position absolute
so that the context menu will show where we right-click on the mouse.
And we set display
to none
so that we don’t show the menu initially.
Next, we add the event listeners by writing the following JavaScript code:
const ctxMenu = document.getElementById("ctxMenu");
window.addEventListener("contextmenu", (event) => {
event.preventDefault();
ctxMenu.style.display = "block";
ctxMenu.style.left = (event.pageX - 10) + "px";
ctxMenu.style.top = (event.pageY - 10) + "px";
});
window.addEventListener("click", (event) => {
ctxMenu.style.display = "";
ctxMenu.style.left = "";
ctxMenu.style.top = "";
});
We call window.addEventListener
to listen to the events on the whole page.
In the contextmenu
event handler, we call event.preventDefault
to prevent the default action when we right-click, which is to open the browser’s context menu.
Then we set display
to 'block'
to show the ul
as a block-level element.
And we set left
and top
to the position where the mouse pointer is right-clicked.
In the click
event listener, we set the display
, left
and top
properties all to an empty string to remove all the styles and use the ones from CSS.
Now when we right-click on the page, we see our context menu displayed instead of the browser’s menu.
Conclusion
We can create our own context menu on a web page by creating our own HTML, CSS, and JavaScript code.