Disable Context Menu for Specific Elements on a Page

Protected Image

The context menu (right-clicking) for the image above is disabled (except in Opera). For the JavaScript to work the image must have class="protect".

Unprotected image

This image (above) does not have the context menu disable because it does not have class="protect".

One more thing you need to do to thwart IE users is to disable the image toolbar. Add the following meta tag to your page:

<meta http-equiv="imagetoolbar" content="no">

JavaScript used

function disableContextMenu() { // grab all images and loop through them checking for the class to have "protect" in it. // This function won't work in Opera becuase it doesn't support .oncontextmenu var images = document.getElementsByTagName("img"); for(var i=0;i<images.length;i++) { //get the image's class and see if "protect" is in it if(images[i].className.indexOf("protect") != -1 ) { // disable the context menu for this image. images[i].oncontextmenu=function(){return false;}; } } }

Disable context menu for all images

The only change you need to make to disable all context menus for all images is to remove the if statement that checks for class names.

function disableContextMenu() { // grab all images and loop through them. // This function won't work in Opera becuase it doesn't support .oncontextmenu var images = document.getElementsByTagName("img"); for(var i=0;i<images.length;i++) { // disable the context menu for this image. images[i].oncontextmenu=function(){return false;}; } }

See also