0

I am confused about events and event handlers, sometimes we call a function with an event handler and put a parameter for it and sometimes we do not. when do I put parameters and when is it necessay?

Here is an example:

<!DOCTYPE html>
<html>
<body>

<h2 onclick="showCoords(event)">Click this heading to get the x (horizontal) and y (vertical) coordinates of the mouse pointer, relative to the screen, 
when it is clicked.</h2>

<p><strong>Tip:</strong> Try to click different places in the heading.</p>

<p id="demo"></p>

<script>
function showCoords(event) {
  var x = event.screenX;
  var y = event.screenY;
  var coords = "X coords: " + x + ", Y coords: " + y
  document.getElementById("demo").innerHTML = coords;
}
</script>

</body>
</html>

where the showCoords has a parameter called event. This code is from W3Schools.

  • 3
    "This code is from W3Schools." — That explains why it is so bad. – Quentin Apr 25 '22 at 20:59
  • That parameter is provided by the browser when the corresponding event happens, and is the object representing it. You provide that parameter in your definition therefore when you need to access information from that object, or call its methods like eg `preventDefault`. If you don't need it - which is not infrequent - then you don't need to specify it, because if you do it will be an unused variable. (But there's no harm in using it either.) – Robin Zigmond Apr 25 '22 at 21:09
  • (I just realised the above isn't strictly true because you're using an inline `onclick` rather than adding event handlers in JS the proper way - see @Quentin's answer for the details. But ultimately the `event` parameter will hold the same thing so the above should still hold.) – Robin Zigmond Apr 25 '22 at 21:11

1 Answers1

0

When you use an intrinsic event attribute (which have all sorts of issues) the variable event references the deprecated global event object.

So if you do this:

<button onclick="foo(event)">

function foo(event) {

}

You read window.event in the onclick function and pass it as an argument to the foo function.

While if you do this:

<button onclick="foo()">

function foo() {
    console.log(event)
}

Then you read window.event directly in the foo function.


When you use addEventListener (the modern approach to binding events that was introduced at the end of the last century):

function foo(event) {
    console.log(event)
}

document.querySelector('button').addEventListener('click', foo);

… then the event listener function (foo) will be passed a (non-deprecated) event object.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I think you meant to include `event` as a parameter of the `foo` function in your last example. – Jack A. Apr 25 '22 at 21:07