Introduction
A context menu is a pop-up menu that provides shortcuts for actions the software developer anticipates the user might want to take. User interaction with context menus depends upon the computing device, its operating system (OS) and it input mechanisms. If the user does not have a mouse, for example, he may access context menus by pressing a keyboard combination, pressing and holding a trackball, holding a tap on a touch screen or placing two fingers on a touch pad. Context menus can be closed by selecting an action or clicking outside the menu area in open space.
Context menu in different OS
Windows
Mac
Ubuntu
Pen designing
Let's plot an outline of the requirements,
- Need an event listener on right click.
- On right click, i need to show a div with list of options(button).
- On clicking outside, context menu should disappear.
- By default, the context menu should pop to the right side of the pointer.
- But while clicking on the edges we need to reposition it so that its within Viewport Height (VH) and Viewport Width (VW).
Edgecase: Positioning box when clicked on edges/corners.
On clicking, we will have the co-ordinate of that point (i.e,) pageX and pageY. We can get the width and height of the screen using window object; window.innerWidth
and window.innerHeight
.
We can find whether the screen is oveflowing using the below code,
const widthOverflow = e.pageX + ctxWidth > window.innerWidth;
const heightOverflow = e.pageY + ctxHeight > window.innerHeight;
We will get a boolean values, based on the boolean values we can further place the context menu.
const ctxHeight = contextmenu.offsetHeight;
const ctxWidth = contextmenu.offsetWidth + 5;
const widthOverflow = e.pageX + ctxWidth > window.innerWidth;
const heightOverflow = e.pageY + ctxHeight > window.innerHeight;
ctxPosition = {
pageX: widthOverflow ? e.pageX - ctxWidth - 5 : e.pageX,
pageY: heightOverflow ? e.pageY - ctxHeight : e.pageY
};
Code Base.
HTML
CSS
JS
Live Tryout
Please right click inside the box.
- External Link: syedjafer.github.io/custom-context-menu/ind..
- Github: github.com/syedjafer/custom-context-menu