6

Super-technical drawing

In the highly-artistic drawing above, the green square is a child of the pink one. The pink one is wrapped around the green one by my function, so the green square could be anything - a hyperlink, an image, button, etc.

I want to capture a click on the pink div ONLY if it isn't a click on the green element too.

This could be done by flipping a Boolean using mouseenter on the green square, but that seems a messy way to do it to me.

Any clues?

IMPORTANT EDIT: I can't mess with the green square at all, so no adding anything to the click event.

Grim...
  • 16,518
  • 7
  • 45
  • 61
  • 3
    I am most upset that SO wouldn't let me create the new tag 'exciting image' =[ – Grim... Sep 14 '11 at 14:47
  • does this thread: http://stackoverflow.com/questions/6635659/jquery-bind-click-anything-but-element is about the same issue as yours? – JMax Sep 14 '11 at 14:50
  • Six months later and now I can create my own tags - not sure I will, though =] – Grim... Feb 15 '12 at 11:09

5 Answers5

9

You can do this:

$('.pink-box-selector').click(function(e) {
    if ($(e.target).is('.pink-box-selector')) {
        // do stuff here
    }
});
jmar777
  • 38,796
  • 11
  • 66
  • 64
  • Just as a side note, one of the advantages of this solution is that you don't have to modify the code based on what element you wrap (since you said that the wrapped element may vary). It's basically white-listing, vs. black-listing. – jmar777 Sep 14 '11 at 14:54
  • you can also just use `$(e.target).is(this)` to avoid referencing the selector twice, might make maintenance easier in the future – Brian Leishman Nov 19 '19 at 21:54
7

Two options. You can first either check if the target is the green div.

$('#pinkdiv').click(function(e) {
  if ($(e.target).is('#greendiv')) return;
  // handle the event
});

Or you can write the click handler for the pink div normally and stop clicks on the green div from propagating.

$('#greendiv').click(function(e) {
  e.stopPropagation();
});
Michael Mior
  • 28,107
  • 9
  • 89
  • 113
1

Would $("#div_id :not('#excluded_element')).click(); help? http://api.jquery.com/not-selector/

Jorge Guberte
  • 10,464
  • 8
  • 37
  • 56
  • 1
    This selector would select nothing. It would look for something *inside* of `#div_id` that *isn't* the only element that's actually in there. – jmar777 Sep 14 '11 at 14:52
0

Setup a separate click event listener for the "green" element and have it event.preventDefault()

Brandon
  • 1,997
  • 3
  • 24
  • 33
0

http://jsfiddle.net/rlemon/d8qVp/

$("#pink").click(function(){
    if(!$("#green").is(":hover")) {
        alert('here');   
    }
});
rlemon
  • 17,518
  • 14
  • 92
  • 123