View Full Version : How to set onContextMenu for image?

10-09-2008, 12:47 AM
I am trying to disable the menu which appears when a user right-clicks on an image. Using the onContextMenu directly in the IMG tag like this seems to do the trick.

<img src="/graphics/dotgrey.gif" width="25" height="25" onContextMenu="return(false)">

However, setting this dynamically with Javascript does not seem to work.

<img src="/graphics/dotgrey.gif" width="25" height="25" id="myimage">

<script language="JavaScript" type="text/javascript">

document.getElementById('myimage').onContextMenu = 'return(false)';


Can anyone suggest a correct way of doing this with Javascript?

10-09-2008, 03:12 AM
First, though it has nothing to do with the script, remove the language attribute. It's deprecated.

For your problem, try this:

document.getElementById('myimage').oncontextmenu = function()
return false; // Cancel any event from this point forward

...also remember that JS is case-sensitive. onContextMenu is different from oncontextmenu

Hope that helps.

10-09-2008, 03:50 AM
works, thanks

12-28-2008, 10:03 AM
What if I intend to do it for all images?

Philip M
12-28-2008, 02:42 PM
What if I intend to do it for all images?

<script type = "text/javascript">
function protect(e) {
return false;

function trap() {
document.images[i].onmousedown = protect;

<body onload="trap()">

12-28-2008, 05:55 PM
It did the trick, all right! Thank you very much Mr. Philip M! :cool:

I have this follow-up: Is it possible for the function to work only on images under a certain class (CSS)?

Edit: The code works in both Firefox and IE when I'm offline. However, when I upload the files, it no longer works in IE.