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,
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.
To capture the right-click event in JavaScript, we can listen for the contextmenu event. el. addEventListener( "contextmenu", (ev) => { ev. preventDefault(); //... }, false );
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With