Web Programming Notes

July 27, 2007

Javascript ContextMenu Script

Filed under: Javascript — admin @ 2:08 pm

The ContextMenu script allows you to define a contextmenu to show when any html element is ‘right-clicked’.   The standard browser contextmenu is disabled, but only for the elements that trigger a custom ContextMenu.  The menu shown can differ for each element.

Please view the example.  — or — Right-click on the element below!


Test element 1

The functionality is:

  1. When a designated element is clicked the assigned context menu is displayed
  2. When the document is clicked the context menu disappears, which is the same as the browser’s implementation.

To get it working:

  1. Include the ContextMenu.class.js file in the HEAD of your document.
  2. Create a trigger element that will fire the context menu: e.g.
    <div id=’trigger’>Right-Click Here</div>
  3. Create a menu to show e.g.
    <div id=’contextMenu’ style=’display: none; position: absolute;’>…Menu Goes here…</div>
  4. Assign the ‘menu’ to the ‘trigger’ with a simple Javascript call.
    <script>var cm = new ContextMenu(’trigger’,'contextMenu’);</script>

The implementation does not rely on any additional js libraries and should not impact on any existing JavaScript code.  It ’should’ fail gracefully.  You can define as many instances of ‘ContextMenus’ as you like on a single page without repeating any unnecessary code.

The script is based on code from various places including:

http://simonwillison.net/2004/May/26/addLoadEvent/ : I applied a similar technique to the document.onmousedown event so that existing handlers are not overwritten.

http://luke.breuer.com/tutorial/js_contextmenu.htm : The basic ideas were taken from here.

The script has been tested in IE6 and Firefox 2

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress