Helping ordinary people create extraordinary websites!
GET OUR NEWSLETTER
Your Email:
 

JavaScript No Right Click

<body oncontextmenu="return false;">

We covered JavaScript Events, where a particular event occurs as part of a particular element of the page. When a right click occurs, the "context menu" event of the main document (i.e. <body>) is fired. We can prevent a right click menu from appearing simply by returning false; this tells the browser that the action (technically, the click) failed and the associated actions should not continue.

Reasons to alter right click menu

Long ago, blocking right click could prevent users from copying your content or viewing your source. Users of early versions of Internet Explorer were accustomed to right clicking and selecting the "view source" option; blocking right click quietly prevented this. Today, the simplest way to view the source of a page in the latest version of Internet Explorer requires a right click, as the view menu (with an equivalent "View Source" option that cannot be blocked) is not immediately available.

However, many modern browsers include keyboard shortcuts for right click or other means to access the source. In fact, blocking right click can be nothing but an annoyance for users. Rather, blocking right click allows developers to put something in its place. For example, Google's web-based word processing software blocks has a no right click script but replaces the default right click menu with its own, just as you would expect from any word processing software. This allows Google to create powerful applications that make use of a variety of user input methods.

DOM scripting approach

And, of course, this can also be achieved by binding to the body element's event at runtime:

document.body.oncontextmenu = function() { return false; }

Given that this is a JavaScript function, one can easily substitute a dynamically-created context menu here, or perform some other action.

« JavaScript Events JavaScript Strings »

More JavaScript Tutorials:
» Label Within The Form Field - Handling
» Client-side Validation with Javascript
» How to Disable the Submit Button
» Automatic Page Events
» Striped Tables Using JavaScript
» Finding the Length of a String in JavaScript
Advertise with Us!


Learn JavaScript Tutorials Scripts