How to Create a Right-Click Menu using JQuery
In this tutorial, we will create a right-click menu (better known as a context menu) that will come up when you right-click on the page …
For Mac, you would do Ctrl-Click, since Mac mouse have only one button. Normally, when you right-click on a webpage you get the browser’s context menu. But we are going to override that and show our own custom context menu instead.
While this can be done via Javascript, we are going to use jQuery because I can not remember all the cross-browser tricks I have to do to get the proper mouse position.
1. We start with basic HTML5 page with some dummy text …
For the sake of simplicity, we placed the script and the styles within the same page. In production environments, they are likely to be separate files.
2. In our Javascript, we capture the contextmenu event which will give us the event e in our callback …
3. When we right-click on our page and trigger the contextmenu event, and console out the e, we see that it gives us pageX and pageY information on where the mouse was clicked in relation to the upper-left of the document …
4. This is where we will display our context menu by setting the left and top properties of our contextMenu and cancelling the default right-click action of the browser by calling e.preventDefault() …
5. Our context menu will be assigned an id of “contextMenu” and we use “css” jQuery method to set the left and top position based on e.pageX and e.pageY. Remember to append the “px” suffix to these coordinates.
6. Shown above (just above the closing body tag), our context menu consists of an “nav” element with an “ul” and “li” elements containing links. In order to place this menu where ever we like, we need to position absolute this nav element in relation to the body element…
7. We don’t want the menu to show unless a right-click occurs. So we set display to none initially…
8. And then show the menu when contextmenu event is triggered…
9. When you render this in the browser and right-click you now have …
10. We need some styling on the menu like this …
11. The one final thing is to let the user close the menu when they click outside of the menu. So we have to capture the click event on the document …
But clicking on the links in the menu or in the document still works as usual.
12. The menu can go off the screen or otherwise positioned weirdly if the menu is open and user resizes the screen. So we hide the menu upon screen resize as well…
Note that we attached the resize event to the window object instead of the document object.
13. Now we got the final context menu …