Disabling the Context Menu - DHTML Lab - DHTML Diner | 2 | WebReference

Disabling the Context Menu - DHTML Lab - DHTML Diner | 2

DHTML Diner Logo

Disabling the Context Menu


Netscape Navigator allows us to disable the context menu across platforms using the same logic.

In fact, it is not a special logic. It applies to all events.

That is, any event that returns a value of false cancels the default action associated with that event.

The classic example that we all know is the following. Click on the link below:

Go to WebReference home page

No navigation occurs because the HTML used to create the link looks like this:

<A HREF="http://www.webreference.com"
    onClick="return false">Go to WebReference home page</A>

The default action associated with the click event in the <A> tag is browser navigation to the value of the HREF attribute. In our example, we defined an onClick event handler that handles the click event first. We could have included a function call, or a series of statements, all of which would be executed before the link was followed. By returning false from the event handler, however, the link is not followed. This example works with all browsers.

The next example works only with Navigator, and IE for Macintosh. Try to get a context menu from the two images:

with context menu

without context menu
<IMG SRC="diner.gif"
<IMG SRC="diner.gif"
onMouseDown="return false">

By including an onMouseDown handler in the IMG tag, and returning false, the default action (showing the context menu) is cancelled.

Therefore, for Navigator and IE for Macintosh, the context menu is connected with the mousedown event, and can be easily disabled by returning false from the event handling.

What authors usually ask for, however, is a way to disable the context menu throughout the document, except for links and images. They are trying to avoid the inadvertant apprearance of the menu when a user lazily clicks anywhere.

To achieve this in Navigator, we need the following statements:

window.onmousedown = function(e){
    if(e.target==document)return false;

We capture the mousedown event for the complete window. The function that is assigned to the event handler, checks the target property of the implicitely-passed event object, e. Any element that can handle a mousedown event, like a link or image, will appear as the target property. If no mousedown-enabled element is under the mouse, target will be the document itself.

Therefore, if we mousedown on the document, the function returns false and no context menu appears.

Now, let's do the same for Explorer.

Produced by Peter Belesis and

All Rights Reserved. Legal Notices.
Created: April 28, 2000
Revised: April 28, 2000

URL: http://www.webreference.com/dhtml/diner/contextmenu/2.html