JQuery on('contextmenu') for body, but special one class

contextmenu, events, jquery, jquery-events

Solution

It's quite simple, you just need to stop the event from propagating further than your `.tiny` handler.

$('.tiny').on('contextmenu', function(e){
  e.stopPropagation();
  // Your code.
});

Assuming you may have a whole lot of `.tiny`'s, or they're dynamically generated, you could delegate this event to `.all`:

$('.all').on('contextmenu', '.tiny', function(e){
  e.stopPropagation();
  // Your code.
});

Another option is to check the `e.target`.

$('body').on('contextmenu', '.all', function(e){
  if(!$(e.target).hasClass('.tiny')){
    // The target element is not a .tiny div
  }
});

Then you'd just have your other normal handler for `.tiny`

Problem

I have a big div (whole page) and inside of it I have smaller one: ``` <div class="all"> <div class="tiny"></div> </div> ``` `div.all` is like a board for me, `div.tiny` is a little rectangle on it. I want to show my special context menu any time anything (or nothing) in `div.all` will get RMB. But when I RMB on `div.tiny`, I don't want to execute that "default" procedure, but some (even more special) code. I have tried with: ``` jQuery('body').on("contextmenu", ".all", function(){ /* special stuff */}); jQuery('body').off("contextmenu", ".all .tiny"); /* <- tried to turn off my...*/ /*...special stuff for .tiny that way*/ jQuery('body').on("contextmenu", ".tiny", function(){ /* even more special stuff */ }); ``` When I run it, RMB on `div.all` or elements inside of it, I get "special stuff" done. But when I click RMB on `div.tiny` I get both "special stuff" (which I don't want) and "even more special stuff" (it's so special, how I cannot want it!). Any solution? To make life harder, I cannot change the order (the first `jQuery()` for `div.all`, THAN my functions for `div.tiny`) - in my real project things are more complicated and I have to keep that order for some reasons (still it's look pretty reasonable - from global events to precise one).

Original source