Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
29
rated 0 times [  36] [ 7]  / answers: 1 / hits: 11859  / 3 Years ago, sun, february 7, 2021, 12:00:00

I am learing event.target and event.currentTarget. I think i am clear with the difference between the two. But stuck in a situation where event.currentTarget value turns out to be null.


Following are the HTML and JS code snippets:


HTML code


<form id="form">
This is a form
</form>

JavaScript Code


 form.addEventListener('click', func);

function func(event) {
console.log(event.target.tagName); //line1
console.log(event.currentTarget.tagName); //line2

setTimeout(()=> {
console.log(event.target.tagName); //line3
console.log(event.currentTarget.tagName); //line4
}, 0) ;
}

My doubt is that in line1 and line3 I got the value of event.target the same. But there is a difference in the value of event.currentTarget in line2 and line4.


The output in line3 is 'form', but in line4 it is:



Uncaught TypeError: Cannot read property 'tagName' of null.



That means currentTarget is null in line4.


Can you explain why value of currentTarget is null in line4 ?


More From » dom

 Answers
10

https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget. Note the line



Note: The value of event.currentTarget is only available while the event is being handled. If you console.log() the event object, storing it in a variable, and then look for the currentTarget key in the console, its value will be null`.



[#1829] Monday, February 1, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
miranda

Total Points: 655
Total Questions: 110
Total Answers: 121

Location: Netherlands
Member since Thu, Jul 1, 2021
3 Years ago
miranda questions
Sun, Jun 6, 21, 00:00, 3 Years ago
Tue, Mar 16, 21, 00:00, 3 Years ago
Mon, Jan 18, 21, 00:00, 3 Years ago
Fri, Jul 17, 20, 00:00, 4 Years ago
;