views:

644

answers:

2

I am trying to paint cell on a html page, where each cell is a DIV, I need to be able to capture right click event on any of these cells, How can I do that?

<script>
function fn(event)
{
 alert('hello'+event.button);
}
</script>

<div id="cell01"
         class=""
         onclick="fn(event);"
         style="left: 1471px; width: 24px; height: 14px; top: 64px; text-align: center; position: absolute; background-color: rgb(128, 128, 0);">1</div>
+3  A: 

I recommend you check out the event handling page on Quirksmode, as it includes a guide to capturing right clicks as well as a comprehensive guide to avoid cross-browser issues with events.

A word of warning though: Not all browsers allow detecting right clicks by default.

Jani Hartikainen
Beat me to it ;)
roryf
i love how microsoft got it right...
geowa4
+1  A: 

Take a look at this: Javascript - event properties. Value for right mouse button is 2, although also note that it recommends using mousedown or mouseup events rather than click.

Here is a sample from the page showing right click detection:

function doSomething(e) {
    var rightclick;
    if (!e) var e = window.event;
    if (e.which) rightclick = (e.which == 3);
    else if (e.button) rightclick = (e.button == 2);
    alert('Rightclick: ' + rightclick); // true or false
}
roryf
+1 - for the example - although you deserve a +2 since I gave jani a +1 too for being quick on the draw, but you included sample code ;)
Faisal Vali