Welcome to our free JavaScript tutorial. This tutorial is based on Webucator's Introduction to JavaScript Training course.
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:
<!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>
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.)
This tutorial is based on Webucator's Introduction to JavaScript Training Course. We also offer many other JavaScript Training courses. Sign up today to get help from a live instructor.