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
}); */