DEV Community

How to create a custom context menu for your web application

Richard Umoffia on February 13, 2018

Before we begin, here's a preview of what we'll be creating. Let's discuss a few use cases of a custom context menu. You wish to dis...
Collapse
 
kosm profile image
Kos-M

pretty cool post nice !
in addition if someone wants context triggered only on certain element :

window.addEventListener("contextmenu", e => {
    const origin = {
        left: e.pageX,
        top: e.pageY
    };
    var targetElement = event.target
    if (targetElement.nodeName === "TD") {
        e.preventDefault();
        console.log(targetElement)
        setPosition(origin);
    }

    return false;
});
Collapse
 
yannik_sc profile image
Yannik_Sc

The more interesting is: how to extend the existing context menu.

Custom is always bad, it hides the browser's one, looks sometimes odd, if you have a custom OS theme or something like that and it often does not behave, like you would expect it (from the normal one).
This is at least my thinking of it, and there might be more reasons why a custom context menu is bad.

Collapse
 
nexthazard profile image
Jared Richards • Edited

Any Advice to not make the ContextMenu not deform the Page such as Crating a Space over all content so when right clicking the page does not get deformed or not expand (Scrollbars.

Awesome Tut Thx :)

Collapse
 
iamafro profile image
Richard Umoffia

To achieve that Jared, you'll have to set the menu's position to fixed or absolute. I just realised I had set it to relative in the tut. Setting the position to fixed or absolute should solve that. I'm glad you enjoyed the article. Thanks  😇

Collapse
 
humoyun profile image
Humoyun Ahmad

Exactly!

Collapse
 
pbkarlsson profile image
Philip Karlsson

Cool, I've always thought that it's super-complicated and that's why so few does it. I stand corrected. Thanks :)

Collapse
 
iamafro profile image
Richard Umoffia

I thought so too until I decided to try it. Glad you liked it.

Collapse
 
neurogirl47 profile image
Udochi Okeke

This is the best explanation on this topic I have seen! Thanks!

Collapse
 
ahmadsuleiman profile image
ahmadsuleiman

how to add sub list to list item?

Collapse
 
abishekaasaari profile image
Abishek Aasaari

But when we click near the edge of the screen the context menu is hidden by the edge of the screen. Is there any solution for that ?

Collapse
 
midnightlead profile image
Ivan O

Also, here is a problem with the menu if you call to at page's bottom and/or right.
setPosition should be more complex. Consider to page and menu size.

Collapse
 
allaboutcode profile image
All-About-Code

Does not work for me on Opra,Chrome, and Firefox!

Does not work!

Collapse
 
chandan11krish1 profile image
chandan krishna

i'm getting some problem when right button is clicked the margin at the top is extending with blank space...
So please anyone suggest solution for the problem...
email : chandan11krishna@gmail.com