Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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,

like image 338
Pez Cuckow Avatar asked Jun 04 '10 10:06

Pez Cuckow


People also ask

How do I disable right click on a specific div?

We can disable the right-click menu on the web page by preventing the default behavior when the right-click event happens. The contextmenu event will be fired when user right-clicks on a div. We can bind an event listener for that event and prevent the default behavior.

How can I capture the right click event in Javascript?

To capture the right-click event in JavaScript, we can listen for the contextmenu event. el. addEventListener( "contextmenu", (ev) => { ev. preventDefault(); //... }, false );

How do I hide the context menu in right click?

The context menu usually has a list of actions like "View Page Source" and "Back". We can prevent this menu from appearing on right-click by latching onto the contextmenu event and using event. preventDefault() . If we add this event listener to the window object then we can prevent right-clicking on the whole page.


1 Answers

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...

like image 157
ryanulit Avatar answered Sep 21 '22 23:09

ryanulit