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

Preventing an Event from Performing Its Default Behavior

NN 6, IE 5

Problem

You want to prevent an event from triggering its default behavior.

Solution

Although it is a fruitless endeavor to use scripts to block users from, say, right-clicking on an image to save a copy of the image on the local hard disk, this recipe shows how to use event blocking to discourage casual users who may be dissuaded by an alert message.

The primary event to block in this case is the oncontextmenu event, which is implemented in IE 5 or later for Windows and Netscape 6 or later. Assign a function to the event at the document level. The following function blocks the event for all img elements:

function blockEvents(evt) {
    evt = (evt) ? evt : event;
    var blockit = false;
    var elem = (evt.target) ? evt.target : ((evt.srcElement) ? 
        evt.srcElement : null);
    if (elem && elem.tagName && elem.tagName.toLowerCase( ) =  = "img") {
        if (evt.cancelBubble) {
            evt.cancelBubble = true;
        }
        alert("Sorry, feature not available.");
        return false;
    }
}
document.oncontextmenu = blockEvents;

Discussion

Inhibiting an event's default action can give your dynamic pages powers they couldn't have on their own. For example, if you want to limit text field entry to numbers only, examine the event object details and block nonnumeric characters from reaching the field. Similarly, if you are performing client-side form validation (see Chapter 8) when the user submits the form, you want to block the submit event from carrying out its default behavior ...

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