...

View Full Version : How to set onContextMenu for image?



>ssp-cdr<
10-09-2008, 01: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)';

</script>


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

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

For your problem, try this:


window.onload=function()
{
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.

>ssp-cdr<
10-09-2008, 04:50 AM
works, thanks

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

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




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

function trap() {
for(i=0;i<document.images.length;i++)
document.images[i].onmousedown = protect;
}
}
</script>

<body onload="trap()">

simulationelson
12-28-2008, 06: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.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum