I've read many posts about this 'e' and about arrow functions, but I don't get it.
myDiv.addEventListener('mousedown', e => {
x = e.clientX;
y = e.clientY;
console.log(x);
});
I've read many posts about this 'e' and about arrow functions, but I don't get it.
myDiv.addEventListener('mousedown', e => {
x = e.clientX;
y = e.clientY;
console.log(x);
});
That code calls the addEventListener
method on the myDiv
object, which I assume is an HTML element. It passes in two arguments:
'mousedown'
, a string telling addEventListener
what event to attach the event handler to, and
e => {/*...*/}
, the event handler function to attach
Later, if the mousedown
event occurs for that element, the browser will call the event handler function with an Event
object as the only argument to the handler. The handler receives that argument in its e
parameter and uses properties on that Event
object (clientX
and clientY
), assigning them to the variables x
and y
and then outputting x
to the browser console via console.log
.
I should note that unless x
and y
are declared in code you haven't shown, that event handler falls prey to what I call The Horror of Implicit Globals by assigning to undeclared identifiers. If x
and y
are meant to only be used within the event handler function, they should be declared there with const
or let
:
myDiv.addEventListener('mousedown', e => {
const x = e.clientX;
const y = e.clientY;
console.log(x);
});
(There's also no reason to assign to y
unless it's being used for something.)
/*object*/.addEventListener(/*type*/, (e) => { /*code*/ });
The e
parameter refers to the event that occurred, causing the listener to fire.
The callback takes the parameter that is automatically accessible.
2) What is clientX and clientY? These are the positions of the client when the user fired the event.