tags:

views:

28

answers:

1

Trying to wrap my head around the jQuery ".not()" function, and running into a problem. I would like to have the parent div to be "clickable" but if a user clicks on a child element, the script is not called.

$(this).not(children()).click(function(){
   $(".example").fadeOut("fast");
});

the html:

<div class="example">
   <div>
      <p>This content is not affected by clicks.</p>
   </div>
</div>
+2  A: 

To do this, stop the click on the child using .stopPropogation:

$(".example").click(function(){
  $(this).fadeOut("fast");
}).children().click(function(e) {
  return false;
});

This will stop the child clicks from bubbling up past their level so the parent won't receive the click.

.not() is used a bit differently, it filters elements out of your selector, for example:

<div class="bob" id="myID"></div>
<div class="bob"></div>

$(".bob").not("#myID"); //removes the element with myID

For clicking, your problem is that the click on a child bubbles up to the parent, not that you've inadvertently attached a click handler to the child.

Nick Craver
thanks nick, I do not think that this is what i was looking for. I am sorry that I was not clear in my question. I want the entire div.example to fadeOut, only when the parent element is clicked, not when the child div is clicked. The reason for this is I would like the user to be able to click on the paragraph text and not have the text fadeOut. If the user clicks on the outer div (parent div), then everything will fade out.
superUntitled
@superUntitled - Thanks for the clarification...answer's updated to do this, give it a try.
Nick Craver