Disable right clicking on images only

There are few instances where disabling someone’s context menu is appropriate. In most cases it’s unnecessary and can even lead to infuriating your visitors.

Here are some ways to target all the image elements on a page while leaving the rest of the hypertext in peace.

JavaScript

Lightweight, no framework required and works well in IE 6, 7, 8, Chrome, FireFox and Safari. Demo »

document.oncontextmenu = context_menu;

function context_menu(e) {
if (!e) var e = window.event;
	var eTarget = (window.event) ? e.srcElement : e.target;

	if (eTarget.nodeName == "IMG") {
		//context menu attempt on top of an image element
		return false;
	}
}

jQuery

Perhaps the prettiest code of the three. Demo »

$(document).ready(function(){
	$(document).bind("contextmenu",function(e){
		if(e.target.nodeName == 'IMG'){
			//context menu attempt on top of an image element
			return false;
		}
	});
});

MooTools

Moo… Demo »

window.addEvent('domready', function() {
	$(document.body).addEvent('contextmenu', function(e) {
		if(e.target.nodeName == 'IMG') {
			//context menu attempt on top of an image element
			return false;
		}
	});
});

Final Thoughts

With a bit more code you can target specific IDs, class names or any number of elemental combinations. Doing so will limit your context menu friendly fire and keep both you and your users in a happy balance.

Cheers!