Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if child was clicked in Jquery

Tags:

jquery

onclick

Is there a ways in jQuery to tell which child was clicked if the onclick event was binded to the parent?

For instance:

  $('#daddy').click(function () {
    // if($("#son").isClicked()){return true;}
    //return false;
  });

and the markup looks like:

<div id="daddy">
  <span id="son"></span>
  <span id="daughter"></span>
</div>
like image 870
Du3 Avatar asked Feb 29 '12 18:02

Du3


2 Answers

The event handler you pass to click will receive an event object as its first argument. The target of the event (i.e. the element that initiated the event) will be specified there.

Here's an example from the jQuery documentation:

<!DOCTYPE html>
<html>
<head>
  <style>
span, strong, p { 
  padding: 8px; display: block; border: 1px solid #999;  }
    </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>

<div id="log"></div>
<div>
  <p>
    <strong><span>click</span></strong>
  </p>
</div>
<script>

$("body").click(function(event) {
  $("#log").html("clicked: " + event.target.nodeName);
});

</script>  
</body>
</html>
like image 59
FishBasketGordo Avatar answered Sep 22 '22 06:09

FishBasketGordo


You can use the event.target to determine what was clicked:

  $('#daddy').click(function (e) {
      alert(e.target.id); // The id of the clicked element
  });

Here's a simple example.

like image 24
Pat Avatar answered Sep 19 '22 06:09

Pat