Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

event.currentTarget issue

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?

like image 353
kinsho Avatar asked Jan 18 '13 15:01

kinsho


People also ask

What is event currentTarget?

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.

What is the difference between event target and event currentTarget?

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.

Why is currentTarget null?

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.

What is e currentTarget ID?

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.


1 Answers

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.
       }
    });

})
like image 197
kinsho Avatar answered Oct 19 '22 23:10

kinsho