<div oncontextmenu="asdf(event)">
<script type="text/javascript">
function asdf(event){
if (event.ctrlKey)
alert('foo');
}
</script>
Why this works: inside the anonymous function created by an event handler attribute string, there is a local variable event
initialised to point to the Event instance. IE has a broken event model, but this code still works because the event
now refers not to a local variable but the window.event
global.
However you would generally want to avoid event handler attributes these days. Better to assign event handlers from script itself, eg.:
<div id="thing">
<script type="text/javascript">
document.getElementById('thing').oncontextmenu= function(event) {
if (event===undefined) event= window.event; // fix for IE
if (event.ctrlKey)
alert('foo');
};
</script>
Putting it in script also means your HTML stays validatable. (oncontextmenu
is an IE extension that won't be standardised until HTML5.)
You can also migrate the same function to addEventListener
, but note that IE doesn't support it so you need to sniff for the presence of addEventListener
and if missing use the IE-specific attachEvent
instead. If you don't need multiple handlers for the same event on the same object it is easier (and more compatible with ancient browser) to just use the old-school onevent
-style handlers instead.
Note that contextmenu
is an unreliable event. It isn't supported in all browsers, may be disabled or may always still bring up the browser's real context menu, and on a Mac a common way to get it is with Control-click, which may confuse your check for ctrlKey
. Plus of course there are accessibility issues. Use context menus in web applications as a shortcut feature only, not as an essential access method.