• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

9. Managing Events > 9.4. Preventing an Event from Performing Its Default Behav...

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;

PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint