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.
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.