I was debugging an issue in my javascript code with a variable not being properly set. After a little research, I found out that the variable was not being populated because it was taking its value from an event property that didn't exist. In this case, it was deriving its value from event.currentTarget, which was strangely null.
So I'm a little baffled now. I always though that event.currentTarget always pointed to whatever element held the listener that fired the event. So under what circumstances would event.currentTarget actually be null?
currentTarget. The currentTarget read-only property of the Event interface identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to Event.
event. currentTarget tells us on which element the event was attached or the element whose eventListener triggered the event. event. target tells where the event started.
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 . Save this answer.
event.currentTarget is a property of the event object which identifies the specific HTML element the event listener was attached to. In our case, the div is our event.currentTarget.
All right, I finally figured this out.
The problem was with the way the event was being handled. As you can see below, the event object itself was not only to be processed by its respective handler function; it was also going to be processed by another function that was invoked only when an AJAX call that was made in the handler returned successfully. However, once the success function executes under the AJAX call, the event object loses some of its context, namely its currentTarget property. I presume that the reason why this is is because we're not directly within the scope of the handler once the browser starts executing code within the success function.
$('#element').click(function(e) {
// bunch of lines of code here
$.ajax({
type: 'POST',
url: // url,
...,
success: function(response) {
// more lines of code here
callAnotherFunction(e);
// When we invoke the above function, we pass the event in as a
// parameter, but the event has already lost some of its context
// due to scope change.
}
});
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With