Categories:

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="http://www.codingforums.com">Coding Forums</a><br />
<a href="http://www.dynamicdrive.com">Dynamic Drive</a><br />
<a href="http://www.cssdrive.com">CSS Drive</a><br />
<a href="http://www.javascriptkit.com/jsref/">JavaScript Reference</a><br />
<a href="http://www.builder.com/">Builder.com</a><br />
</div>

<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){
el=document.getElementById("context_menu")
contextisvisible=1
if (mozilla){
el.style.left=pageXOffset+e.clientX+"px"
el.style.top=pageYOffset+e.clientY+"px"
el.style.visibility="visible"
e.preventDefault()
return false
}
else if (ie){
el.style.left=iebody().scrollLeft+event.clientX
el.style.top=iebody().scrollTop+event.clientY
el.style.visibility="visible"
return false
}
}

function hidemenu(){
if (typeof el!="undefined" && contextisvisible){
el.style.visibility="hidden"
contextisvisible=0
}
}

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

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.