Example- creating a context menu

A context menu is one that is shown when the user right clicks the mouse anywhere in the document. Let's apply what we've learned in terms of attaching event handlers in the DOM to create a context menu for both modern browsers and IE6.

Demo: Right click anywhere: 

<div id="context_menu" style="width:150px;border:1px solid black;background-color:#EEEEEE;visibility:hidden;position:absolute;line-height:30px; padding-left: 10px">
<a href="">Coding Forums</a><br />
<a href="">Dynamic Drive</a><br />
<a href="">CSS Drive</a><br />
<a href="">JavaScript Reference</a><br />
<a href=""></a><br />

<script type="text/javascript">

var mozilla=document.getElementById && !document.all
var ie=document.all
var contextisvisible=0

function iebody(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body

function displaymenu(e){
if (mozilla){"px""px""visible"
return false
else if (ie){"visible"
return false

function hidemenu(){
if (typeof el!="undefined" && contextisvisible){"hidden"

if (mozilla){
document.addEventListener("contextmenu", displaymenu, true)
document.addEventListener("click", hidemenu, true)
else if (ie){
document.attachEvent("oncontextmenu", displaymenu)
document.attachEvent("onclick", hidemenu)

A DIV that makes up the context menu is initially hidden using CSS. The event handler "onmouseup" for NS6+/Firefox, and "oncontextmenu" and "onclick" for IE5+ is then dynamically attached to this DIV. We define one function, "displaymenu()" to react to these events. It determines whether the mouse button pressed is the right context menu, and positions then reveals the DIV if this case.

Facebook Fan Page