Context menus are one of those very useful UI widgets that still haven’t reached the HTML spec. There have been attempts, but for now everyone tends to make its own custom implementation.
- Has no dependencies;
- Can be triggered with a click/tap on any element;
- Is fully cross-browser;
Then look no further. It’s much simpler than you think!
An exampleTry clicking this button:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
1 2 3 4 5 6 7 8
That’s the trick: we hide the menu in CSS initially, then show it when the button gets focused and while we’re clicking on the menu itself. This is necessary so that the click actually gets registered. That’s it! No JS trickery involved.
You can attach event listeners to the menu items, e.g. using
document.addEventListener and they’ll work as usual.
Obviously the menu can be opened only by elements that can receive focus, such as buttons. So what about other non-interactive elements? Can we make them focusable too? The answer is yes!
A more complicated example
We want to display a context menu when clicking on the following image:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
The trick here was to add
tabindex. This makes the element focusable, so that it can open the menu on click. Note that if the clickable element is a
<button> or other interactive content (i.e. any focusable element), then you don’t even need this!
I’ve used a
<figure>, but you can use any element you like. Just add
tabindex="-1" to make it focusable, if it isn’t already. You can place the menu anywhere you want in the HTML, as long as you’re able to target it with a CSS selector. Just try not to put a button in a button as that’s invalid HTML, although technically it will still work.
1 2 3 4 5 6 7 8
How do I make the menu appear next to the mouse cursor?
position: absolute to the menu and just make it appear below (or next to) the element you clicked — no need for JS in this case! Anyway, this did the trick for me:
1 2 3 4 5 6 7
What about browser support?
It may not work in some very old browsers, so make sure to test it in the browsers you need to support. This MDN page has some info about what happens to the focus of a button when being clicked/tapped on different platforms. I did some tests myself and it seems to work well everywhere, including mobile browsers.
And that’s it! I hope you found this useful. If you spot any issues, please do let me know by commenting below!