Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a custom right-click menu to a webpage?

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.

like image 744
Registered User Avatar asked Feb 05 '11 19:02

Registered User


People also ask

How do I create a custom right-click menu?

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.

How do you create a context menu in HTML?

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.

How do I enable right click on my HTML page?

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.


1 Answers

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

like image 77
Radek Benkel Avatar answered Sep 19 '22 16:09

Radek Benkel