Reputation: 183
I have an element with an onclick event (set aside the best practice advice for now):
<div onclick="myfunc()">
in the function:
function myfunc(e) {
console.log(e);
e is undefined. If I put this in the console.log, this is undefined
My understanding is that the event should be passed to the handler so that code should output the event object to the console, and this should refer to the div element.
This seems very basic and I am not finding any explanations for why this might happen.
Second EDIT: The comments resulted in my function working, but I still have no answer for why "this" is undefined in the function. I get the result with event.currentTarget, but this throws an error.
EDIT:
Based on the colloquy with Pointy, I put "myfunc(event)" and made the corresponding changes to the myfunc declaration, and console.log printed the event:
PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, pressure: 0, …}
Ok, good, BUT when I look at the listing, it says
currentTarget: null
Shouldn't currentTarget be the div event? Also, this is still undefined, which makes sense if currentTarget is null, but everything I read says that in a handler created that way - directly in the element, that this should refer to the element.
Upvotes: 3
Views: 4493
Reputation: 183
The answers are in the comments, thanks to @Pointy, @Luke Trenaman and @Barmar
Upvotes: 3