What is context menu?
When you right click on browser window, browser will show you a menu containing some common functions.
See following image for reference.
Image may be NSFW.
Clik here to view.
If you want to build your own custom context menu, follow the easy steps below.
Step 1 – HTML
<div id="context-menu"> <ol> <li><a href="#">menu 1</a> </li> <li><a href="#">menu 2</a> </li> <li class="list-devider"> <hr /> </li> <li><a href="#">menu 3</a> </li> <li><a href="#">menu 4</a> </li> <li><a href="#">menu 5</a> </li> <li class="list-devider"> <hr /> </li> <li><a href="#">menu 6</a> </li> <li><a href="#">menu 7</a> </li> </ol> </div>
Step 2 – CSS
Following is CSS declaration for above context menu structure. This will give metro style look to context menu.
#context-menu { z-index: 1000; position: absolute; border: solid 2px black; background-color: white; padding: 5px 0; display: none; } # context-menu ol { padding: 0; margin: 0; list-style-type: none; min-width: 130px; width: auto; max-width: 200px; } #context-menu ol li { margin: 0; display: block; list-style: none; zoom: 0; padding: 5px 5px; } #context-menu ol li:hover { background-color: #efefef; } #context-menu ol li:active { color: White; background-color: #000; } #context-menu ol .list-devider { padding: 0px; margin: 0px; } #context-menu ol .list-devider:hover { /*background-color: #efefef;*/ } #context-menu ol .list-devider hr { margin: 2px 0px; } #context-menu ol li a { color: Black; text-decoration: none; display: block; padding: 0px 5px; } #context-menu ol li a:active { color: White; }
Step 3 – JavaScript
To enable context menu, write down following script.
$(document).ready(function () { try { $(document).bind("contextmenu", function (e) { e.preventDefault(); $("#context-menu").css({ top: e.pageY + "px", left: e.pageX + "px" }).show(100); }); } catch (err) { alert(err); } });
Note: Above script require JQuery to be included in document.
In above script we have set context menu function to our custom function. This function will prevent default context menu of browser and
will show custom context menu.
Here we can add following function when user clicks on document, will hide context menu.
$(document).bind("click", function (event) { $("#context-menu").hide(); });
look at the beautiful metro style context menu tested in IE9.
Image may be NSFW.
Clik here to view.
Enjoy JavaScript…