Simple Context Menu Using JavaScript and HTML


Main page

The main page screen is just to show the context menu when user right-clicks on it.
 
ContextMenu1.png

Context menu (Right click anywhere in the page)

When the user right-clicks on the main page a context menu with two items appears. The following are the two items which appear in the context menu.
  • Google
  • Gmail
ContextMenu2.png

Highlighted first menu item 

After the context menu has appeared, the menu items are highlighted when the mouse is hovered on the menu items. In the image below, the "Google" menu item is highlighted on mouse hover.

ContextMenu3.png
 
Highlighted menu item 

After the context menu is appeared, the menu items are highlighted when mouse is hovered on the menu items. In below image "Gmail" menu item is highlighted on mouse hover.

ContextMenu4.png 

HTML of menu

Following is the HTML markup which creates the structure of the context menu.

The context menu is created using simple table with unordered list with two list items.

ContextMenu5.png 

JavaScript to show menu on right click

In JavaScript, first the menu is initialized using initMenu() function. The initMenu fuction just applies the appropriate CSS to the menu and respective menu items.

This JavaScripts also binds the context menu to the right-click mouse button using showMenu function and also hides the menu when the user left-clicks on the document i.e. the page using hideMenu function.
 
ContextMenu6.png

JavaScript function to show menu on X and Y co-ordinates of mouse right click

The ShowMenu function is called on the right-click of the mouse on the page. This function gets the X and Y coordinates of where the user right-clicks and sets the top and left position to Y and X coordinates. Finally it displays the menu by setting menu display style to "block".
 
ContextMenu7.png