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.

3
  • 3
    I am most upset that SO wouldn't let me create the new tag 'exciting image' =[ Commented Sep 14, 2011 at 14:47
  • does this thread: stackoverflow.com/questions/6635659/… is about the same issue as yours? Commented Sep 14, 2011 at 14:50
  • Six months later and now I can create my own tags - not sure I will, though =] Commented Feb 15, 2012 at 11:09

5 Answers 5

9

You can do this:

$('.pink-box-selector').click(function(e) {
    if ($(e.target).is('.pink-box-selector')) {
        // do stuff here
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

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.
you can also just use $(e.target).is(this) to avoid referencing the selector twice, might make maintenance easier in the future
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();
});

1 Comment

@jmar777's solution for the first option of checking if the target is the pink div may make more sense.
1

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

1 Comment

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

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

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.