Search code examples
javascriptdom-events

Why is event.currentTarget null in my function?


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?


Solution

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