Disable right clicking on images only

March 3, 2010

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 two 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

If you are already loading jQuery then you might perfer this code to the generic JS above. 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;
        }
    });
});

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!