jQuery: Click on *only* this element


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.

You can do this:

$('.pink-box-selector').click(function(e) {
    if ($(e.target).is('.pink-box-selector')) {
        // do stuff here
    }
});

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();
});

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


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


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

$("#pink").click(function(){
    if(!$("#green").is(":hover")) {
        alert('here');   
    }
});