6

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,

Pez Cuckow
  • 14,048
  • 16
  • 80
  • 130

3 Answers3

12

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

ryanulit
  • 4,983
  • 6
  • 42
  • 66
  • This answer is invalid, contextmenu is triggered on right mousedown, not on right click. – Sebastian Nowak Nov 27 '15 at 13:55
  • A bit harsh and nit-picky to downvote an answer that works. Maybe the wording is confusing, but even the Mozilla documentation says "right click" (https://developer.mozilla.org/en-US/docs/Web/Events/contextmenu). Regardless, the code is about simply capturing the "contextmenu" event of a browser and stopping it from showing the menu. – ryanulit Nov 30 '15 at 19:16
0

I'm not a fan of using the right mouse button on web pages. However, if you really want to do it, you could trap the right mouse button as described here. You could block the right mouse button (in other words return false in your event handler) conditionally if the mouse is over your grid cells.

Regarding your bonus question: jquery ui has drag & drop functionality. It's probably easier to use that than rolling your own.

Adrian Grigore
  • 33,034
  • 36
  • 130
  • 210
  • Many thanks, following your advice I've looking at "draggable" and found this http://jqueryui.com/demos/draggable/snap-to.html seems to be what I need for the dragging – Pez Cuckow Jun 04 '10 at 10:59
0

"is it worth looking at a jQuery plugin for drag and drop?"

Only if you don't intend your application to be used on the iPhone O.S with safari, i.e. including iPad, see Safari Web Content Guide: Handling Events

Matt G
  • 1,332
  • 2
  • 13
  • 25