3

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.

Fred Polli
  • 155
  • 1
  • 10
  • Your `onclick` value is a call to the function with no parameter. – Pointy Jun 02 '22 at 13:44
  • If I put anything inside the parentheses, I get a reference error that the parameter is undefined. – Fred Polli Jun 02 '22 at 13:45
  • Correction, if I put anything other than "event" inside the parens. – Fred Polli Jun 02 '22 at 13:47
  • 1
    Add `event`, as in `myfunc(event)`. Or, much better, assign the handler in JavaScript with `addEventListener()`. – Pointy Jun 02 '22 at 13:47
  • I made an edit to the question to show what happened when I put event in as a parameter. – Fred Polli Jun 02 '22 at 13:51
  • The answer to the second part of your question can be found here: https://stackoverflow.com/questions/66085763/why-currenttarget-value-is-null It looks like currentTarget only points to the div when it is actively being handled, so when you log it to the console your event to the console, it will then be null. – Luke Trenaman Jun 02 '22 at 13:55
  • Thank you, Luke (and Pointy). So, you are right about currentTarget. I have it working now with event.currentTarget... leaving me only with the academic question of why this is undefined rather than referring to the div element like everything I have read says it should. – Fred Polli Jun 02 '22 at 14:03
  • You have to write `onclick="myfunc(this)"`. It's only defined inside the `onclick` attribute. – Barmar Jun 02 '22 at 14:23

1 Answers1

3

The answers are in the comments, thanks to @Pointy, @Luke Trenaman and @Barmar

Fred Polli
  • 155
  • 1
  • 10