tadam logo
Did you find an error in the text?
Select this with mouse and press
Ctrl + Enter
Xhtml.co.il Check Spelling
Orphus system

event.target

event.target

Returns: Element

Description: The DOM element that initiated the event.

event.target

version added: 1.0

This can be the element that registered for the event or a child of it. It is often useful to compare event.target to this in order to determine if the event is being handled due to event bubbling. This property is very useful in event delegation, when events bubble.

Examples

Example 1

Display the tag's name on click
$("body").click(function(event) {
  $("#log").html("clicked: " + event.target.nodeName);
});  
The output of the code above will be:

Full source

Display the tag's name on click
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">

<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>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
    $("body").click(function(event) {
    $("#log").html("clicked: " + event.target.nodeName);
  });  
});

</script>

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

  </p>
</div>

</body>
</html>

Example 2

Implements a simple event delegation: The click handler is added to an unordered list, and the children of its li children are hidden. Clicking one of the li children toggles (see toggle()) their children.
  function handler(event) {
   var $target = $(event.target);
   if( $target.is("li") ) {
      $target.children().toggle();
    }
  }
  $("ul").click(handler).find("ul").hide();
The output of the code above will be:

Full source

Implements a simple event delegation: The click handler is added to an unordered list, and the children of its li children are hidden. Clicking one of the li children toggles (see toggle()) their children.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" language="javascript">

$(document).ready(function(){
function handler(event) {
  var $target = $(event.target);
  if( $target.is("li") ) {
    $target.children().toggle();
  }
}
$("ul").click(handler).find("ul").hide();

});
</script>

</head>
<body>
	
<ul>

  <li>item 1
    <ul>

      <li>sub item 1-a</li>

      <li>sub item 1-b</li>
    </ul>

  </li>

  <li>item 2
    <ul>

      <li>sub item 2-a</li>
      <li>sub item 2-b</li>

    </ul>
  </li>  

</ul>
</body>
</html>
Was this information helpful?
   

Comments