JavaScript: Capturing right click and disabling menu only within certain element

Pez Cuckow picture Pez Cuckow · Jun 4, 2010 · Viewed 8.2k times · Source

I have coded a jquery script where there is a small grid on screen and using drag and drop users can place tiles on the grid (snaps in place). Currently if you hover over a tile it fades in the option to rotate, but I would much prefer it if you could right click to rotate (making it more natural). I understand blocking right click completely is often frowned upon so was wondering if it was possible just within a particular element, then capturing that event, doing something in JS and disabling the context menu? - that works in every browser.

On a side note, currently I am using jQuery for effects and custom javascript for drag and drop, is it worth looking at a jQuery plugin for drag and drop?

Many thanks,

Answer

ryanulit picture ryanulit · Jun 4, 2010

For capturing the right click, you can use this jquery:

$('#gridID').bind('contextmenu', function(e) {
   // do stuff here instead of normal context menu
   return false;
});

This works in chrome, firefox, and safari. Haven't tested IE. Works in IE too. Only caveat is it doesn't work in Opera apparently. So if you can live with that...