O'Reilly logo

JavaScript & DHTML Cookbook by Danny Goodman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating a Contextual (Right-Click) Menu

NN 6, IE 5(Win)

Problem

You want to display a customized menu of navigation or other options when the user right-clicks (Windows) or holds down the mouse button (in Netscape for the Mac)—actions that normally trigger the browser's internal context menu.

Solution

Use the oncontextmenu event handler that is part of newer browsers to intercept the normal browser action and display a menu of your own design. The example page described in the Discussion demonstrates one way to create a menu out of standard HTML elements as well as the script code that controls each menu's visibility, positioning, and interactivity. Figure 10-1 shows the finished results.

A context-sensitive pop-up menu

Figure 10-1. A context-sensitive pop-up menu

To deploy this recipe on a page of your own design, you need to customize the following items:

  • The HTML for the div context menus, following the model shown in the solution

  • IDs for the span elements surrounding the words and phrases to be highlighted

  • Data in the cMenu object, particularly the string indexes of the object entries (identical to the IDs of the highlighted spans), the IDs of the div context menus for the menuID properties, and the href properties' URLs to which you want each menu entry to lead

Style sheets for the highlighted colors (and style sheets in general) can be modified to suit your design tastes.

All activity begins by assigning ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required