Identifying the Target of an Event

Contact Us or call 1-877-932-8228
Identifying the Target of an Event

Identifying the Target of an Event

Often you will want to take action on the target of an event. For example, in a drag-and-drop application, you click down on an element and drag it around the screen. To write that code, you need to be able to identify which element receives the click.

In most modern browsers, this is done with the target property of the event itself. The following demo illustrates:

Code Sample:

HTMLDOM/Demos/target.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="../Styles/propagation.css">
<script>
	window.onload = function() {
		document.getElementById('outer').addEventListener('click', function(e) {
			findTarget(e);
		});
		document.getElementById('inner').addEventListener('click', function(e) {
			findTarget(e);
		});
		document.getElementById('heading').addEventListener('click', function(e) {
			findTarget(e);
		});
	}
	
	function findTarget(e) {
		e.target.innerHTML += " | click | ";
		e.stopPropagation();
	}
	
</script>
<title>Target</title>
</head>
<body>
	<h1 id="heading">Target</h1>
	<div id="outer">outer
		<div id="inner">inner</div>
	</div>
</body>
</html>

Code Explanation

In your browser, click on any of the elements: outer, inner, or the h1 element and the word "click" will get added to the element.

We can also make use of the currentTarget property: this property will refer to the element to which the event handler was attached, as opposed to the target property (which identifies the element from which the event fired.)

Next