What's the difference between this, event.currentTarget, and event.target?

Question

What’s the difference between this, event.currentTarget, and event.target?

Answer

this: this will refer to the context in which the function is called if we use an arrow function, or this will refer to the context in which this is called if we are using a function expression. If we use a function expression we can use this instead of event.currentTarget.

event.currentTarget: Refers to the DOM element that registered the event.

event.target: Refers to the element that initiated the event.

Example:
index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>this, event.currentTarget, event.target</title>
    <style>
      main, section, h1, span {
        padding: 10px;
        border: 1px solid black;
      }
    </style>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="main.js"></script>
  </head>
  <body>
    <main>
      <section>
        <h1><span>Hello</span> world!</h1>
      </section>
    </main>
  </body>
</html>

main.js

//We can test each scenario by uncommenting one event handler at a time:

//`this` with arrow function:
/* $( "body" ).click(( event ) => {
  console.log(this); //will log the window - [object Window] - to the console no matter which element is clicked
}); */

//`this` with function expression:
/* $( "body" ).click(function( event ) {
  console.log(this.tagName); //will log "BODY" to the console no matter which element is clicked
}); */
 
//`event.currentTarget`:
/* $( "body" ).click(function( event ) {
  console.log(event.currentTarget.nodeName); //will log "BODY" to the console no matter which element is clicked
}); */

//`event.target`:
/* $( "body" ).click(function( event ) {
  console.log(event.target.nodeName); //will log, "SPAN", "H1", "SECTION", or "MAIN" to console depending on which element is clicked
}); */
8 Likes

Thanks for these questions and answers!

The main.js in this answer is missing the jQuery ready method wrapper:

$(document).ready(() => {

});

If I am not mistaken, the event handlers will not work unless this is added?

What is the difference between the arrow function and the function expression? Seems to be the same, but in the lessons only the arrow function is used. Any particular reason or difference?

this doesn’t work with arrow function, Instead, it works fine with anonymous function.

1 Like