0

I am new to Javascript and trying to understand using event.target to reference the element that fired the event. All the documentation says I should pass event as a parameter to any function that requires it, but I have found that event.target works even if I don't pass the parameter.

e.g. all the following work and give the same result:

<button type="button" onclick="f1(event);">Calls function f1 passing event</button>

<button type="button" onclick="f1();">Calls function f1 without passing event</button>

<button type="button" onclick="f2(event);">Calls function f2 passing event</button>

<script>

  function f1() {
    alert(event.target.innerHTML);
  }

  function f2(event) {
    alert(event.target.innerHTML);
  }

</script>

So my question is, what is the point passing event? Is it just considered good practice to send it? Or will some browsers not work if I don't?

I think it looks neater not to have to pass it, so if I can get away without doing so, I'd rather, but I don't want to fly in the face of good practice.

Thanks in advance.

Dean B
  • 1
  • 2
    The ["window.event"](https://developer.mozilla.org/en-US/docs/Web/API/Window/event) is set in most (perhaps all) browsers. It is good practice to pass the "local" event: _The read-only Window property event returns the Event which is currently being handled by the site's code. Outside the context of an event handler, the value is always undefined. You should avoid using this property in new code, and should instead use the Event passed into the event handler function. This property is not universally supported and even when supported introduces potential fragility to your code._ – mplungjan May 13 '20 at 09:10
  • 1
    There's a [global `event` variable](https://developer.mozilla.org/en-US/docs/Web/API/Window/event), and yes you should not use it. You can get away with a lot of things in js that are bad practices. – Bergi May 13 '20 at 09:10
  • Even Firefox has now finally added it. – T.J. Crowder May 13 '20 at 09:11

0 Answers0