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.
According to the answers here and on other 'flows, I've made a version that looks like the one of Google Chrome, with css3 transition. JS Fiddle
Lets start eazy, since we have the js above on this page, we can worry about the css and layout. The layout that we will be using is an
<a>
element with a<img>
element or a font awesome icon (<i class="fa fa-flag"></i>
) and a<span>
to show the keyboard shortcuts. So this is the structure:We will put these in a div and show that div on the right-click. Let's style them like in Google Chrome, shall we?
Now we will add the code from the accepted answer, and get the X and Y value of the cursor. To do this, we will use
e.clientX
ande.clientY
. We are using client, so the menu div has to be fixed.And that is it! Just add the css transisions to fade in and out, and done!
What I'm doing up here
User js to invoke your own actions.
You should remember if you want to use the Firefox only solution, if you want to add it to the whole document you should add
contextmenu="mymenu"
to the<html>
tag not to thebody
tag.You should pay attention to this.
A simple way you could do it is use onContextMenu to return a JavaScript function:
And by entering
return false;
you will cancel out the context menu.if you still want to display the context menu you can just remove the
return false;
line.I know this has already been answered, but I spent some time wrestling with the second answer to get the native context menu to disappear and have it show up where the user clicked.
HTML
CSS
JavaScript
CodePen Example