Implement a custom right-click menu on a web page.




We all work with context menus often while panning around a webpage. They are sometimes also referred to as right-click menus, owing to the fact that they show up when the mouse is right-clicked.

Shown below is an example of a right-click menu in Chrome:

The native context menu on Google Chrome.
The native context menu on Google Chrome.

If you carefully notice it on most of the browsers, the context menu always tries to be aligned with the pointer.

More specfically, the top-left edge of the menu gets aligned with the pointer when there is enough room for the menu to be shown in this way; otherwise, it's bottom edge aligns with the pointer while its right edge aligns with the right edge of the viewport.

It simply depends upon the position of the pointer as to how the menu gets positioned.

In this exercise, you have to implement a custom context menu that gets displayed just like a native context menu, as detailed above.

Your context menu doesn't have to have a whole list of options to select — it should simply be a rectangular box with any dummy option inside it. Let's just say that the width of the menu must be 200px while its height must be 300px.

Note that your code must NOT use these hard-coded dimensions; instead, it must obtain them at runtime so that if we want to change the dimensions, we don't have to make any changes to the JavaScript code.

The sole purpose of this exercise is to get the positioning of the custom menu, and other behavior associated with it, right.

Here's how the final output should look:

Live Example