I want to add a custom right-click menu to my web application. Can this be done without using any pre-built libraries? If so, how to display a simple custom right-click menu which does not use a 3rd party JavaScript library?
I'm aiming for something like what Google Docs does. It lets users right-click and show the users their own menu.
NOTE: I want to learn how to make my own versus using something somebody made already since most of the time, those 3rd party libraries are bloated with features whereas I only want features that I need so I want it to be completely hand-made by me.
To make this HTML menu visible when right-clicking in the browser, we need to listen for contextmenu events. We can bind the event listener directly on the document or we can limit the area that a user can right-click to see the custom context menu. In our example, the area for right-click is the entire body element.
The contextmenu global attribute is the id of a <menu> to use as the contextual menu for this element. A context menu is a menu that appears upon user interaction, such as a right-click. HTML5 now allows us to customize this menu. Here are some implementation examples, including nested menus.
If the page you are on has a text or textarea input, click into this input (as if you want to enter text) then right-click and select 'Inspect element'. Show activity on this post. There you will find Enable right click. Click on it.
Answering your question - use contextmenu
event, like below:
if (document.addEventListener) { document.addEventListener('contextmenu', function(e) { alert("You've tried to open context menu"); //here you draw your own menu e.preventDefault(); }, false); } else { document.attachEvent('oncontextmenu', function() { alert("You've tried to open context menu"); window.event.returnValue = false; }); }
<body> Lorem ipsum... </body>
But you should ask yourself, do you really want to overwrite default right-click behavior - it depends on application that you're developing.
JSFIDDLE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With