Yevgeny Kozlov Yevgeny Kozlov - 4 months ago 19
Javascript Question

JavaScript + Chrome - Event capture

I am trying to figure out how events are working. I have this piece of code:

document.captureEvents(Event.MOUSEMOVE);
document.onmousemove = mousePos;
document.onkeypress = keyPressed;

var keyStroke = 0;
var mouseX = 0;
var mouseY = 0;

function mousePos(e) {
console.log(e);
mouseX = e.pageX;
mouseY = e.pageY;
document.formex.mousex.value = mouseX;
document.formex.mousey.value = mouseY;
return true;
}

function keyPressed(e) {
console.log(e);
keyClicked = e.key;
document.formex.keypress.value = keyStroke;
return true;
}


What confuses me - inside of keyPressed function
console.log(e)
yields KeyboardEvent, inside of
mousePos(e)
it yields MouseEvent. I can't tell how the differentiation between these two 'e' happens?

Answer

What confuses me - inside of keyPressed function console.log(e) yields KeyboardEvent, inside of mousePos(e) it yields MouseEvent. I can't tell how the differentiation between these two 'e' happens?

The browser creates event objects and fires them at the document elements. When the event relates to the keyboard, the browser creates a KeyboardEvent. When it relates to the mouse, it fires a MouseEvent. If it relates to something else, it will create and fire a different kind of event.

The "differentiation" is based on what caused the event to be fired: A keyboard action or a mouse action.