Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assigning click event to div but not anchor within it

A jquery question.

I have a div that contains text and an anchor tag.

I want to assign a click event to the div tag and its content EXCLUDING the anchor tag.

So when I click on the div, an alert window pops up. But if I click the anchor (thats within the div), the alert should not occur.

The div would be something like this:

<div id="myDiv">
    This is the content of the div.
    <img src="blah.jpg" />
    <a href="somewhere.html">Click here</a>.
    Some more content.
</div>

Any ideas? I am using jquery to assign the click event to the div.

like image 721
amateur Avatar asked Oct 14 '10 12:10

amateur


1 Answers

You can check the target of the click since the <a> has no children, for example:

$("#myDiv").click(function(e) {
  if(e.target.nodeName == 'A') return;
  //click handler code
});
like image 103
Nick Craver Avatar answered Oct 18 '22 13:10

Nick Craver