Tags: js
Posted on 26 July 2007, 11:49 by ygleyzer

OnContextMenu

I discover a "new" javascript feature, oncontextmenu attribute.

Overriding this attribute allows to control right-click menu of browser.

An example:
<script type="text/javascript">
function show_context_menu(e){
  alert('JS instead of browser menu !');
  // prevent default right-click menu from appearing.
  //if (browser_type == "IE") 
  if(e){
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation(); 
    if (e.preventDefault) e.preventDefault();
  }
  return false;
}
</script>
<span class="bggray" oncontextmenu="return show_context_menu(event);"> right-click me! </span>
… and result :

right-click me!

It is may be very useful for menu-like control for some elements.

UPD: If oncontextmenu not supported, it may be replaced by catching left-click + shift :

onmousedown="if(event.shiftKey) return show_context_menu(event); else return false;"



Login in order to comment