Registered User Registered User - 2 months ago 17
Javascript Question

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.

Answer

Answering your question - use contextmenu event, like below:

<html>
<head>
<script type="text/javascript">
    if (document.addEventListener) { // IE >= 9; other browsers
        document.addEventListener('contextmenu', function(e) {
            alert("You've tried to open context menu"); //here you draw your own menu
            e.preventDefault();
        }, false);
    } else { // IE < 9
        document.attachEvent('oncontextmenu', function() {
            alert("You've tried to open context menu");
            window.event.returnValue = false;
        });
    }
</script>
</head>
<body>
Lorem ipsum...
</body>
</html>

But you should ask yourself, do you really want to overwrite default right-click behavior - it depends on application that you're developing.


JSFIDDLE

Comments