A right-click menu or context menu in a browser is a menu with multiple choices that appears on right-click mouse operation. It provides multiple functionalities relevant to that particular context. Sometimes, we want the context menu to have more options or features but we cannot modify the default context menu. So, we have to create a custom menu. Adding a custom context menu to your website or webpage makes it look more customized and relevant to the context and offers you the freedom to add desired features to it.
In this article, we will be creating a custom context menu for a webpage. It mainly involves two steps.
- Preventing the default context menu from popping up when the right mouse button is clicked.
- Creating our own custom context menu with HTML and CSS and displaying it on right-click.
Let us go through them in a step by step manner.
HTML code: The following HTML code snippet only shows the HTML page with the default menu which is displayed on right-click event.
If we right-click on this page, the default menu will pop up.
We will create a rightClick() function. In this function, we will call the preventDefault() method of the mouse click event which will cancel the default behavior of the right-click event. We can also return “false” to cancel the event. Now, the default menu will not pop-up on right-click mouse button.
HTML code: The following HTML code demonstrates how to prevent the default right click event.
The default menu is blocked. Let us create our own custom context menu. The context menu we are going to create will be an HTML list. We will also add some CSS to make it look good.
We are creating an unordered list inside a “div” tag with id and class. Add some options to the list. We will keep it hidden by setting the value of “display” property to none.
We will add an event handler for the click event and bind it with the hideMenu() function so that if the user clicks anywhere on the page and the context menu is already being displayed, it hides. Also, we have to place the menu where the right button is clicked. To do this, we will use two properties pageX and pageY of the mouse click event which will give us the coordinates where the right button was clicked. We will hide the context menu on the mouse button click if it is already being displayed.
Output: The following output shows the custom context-menu appearing on the right-click.
On right-click, the menu appears but this is not what we want. We want it to appear where the button was clicked and it should actually look like a menu.
CSS code: We will add some CSS properties for the proper positioning and styling of the menu.
Final code: The following is the combination of the above code snippets.
This was a basic context menu that we created. You can do much more by adding some cool hover effects, shadow effects, coloring, borders, etc.