Question:
What is the difference between using window.addEventListener
and window.document.addEventListener
window.addEventListener("keydown", function(k){
if(k.altKey) {
alert("Solamente window.addEventListener: Tecla [ALT] PRESIONADA");
}
else {
alert("Solamente window.addEventListener: Tecla [ALT], NO PRESIONADA");
}
}, false);
window.document.addEventListener("keydown", function(k){
if(k.altKey) {
alert("Con window.document.addEventListener: Tecla [ALT] PRESIONADA");
}
else {
alert("Con window.document.addEventListener: Tecla [ALT], NO PRESIONADA");
}
}, false);
<html>
<body>
</body>
</html>
Answer:
For this case there is no difference. But maybe these links will be more useful to you: https://www.w3schools.com/jsref/obj_window.asp and https://www.w3schools.com/jsref/dom_obj_document.asp
In it they explain the difference between window
and document
:
document
It is the root component of the application, and all other nodes including window
are hijos
of it. Therefore, when assigning an event to the document, it will always capture it.
Window
It is a component that represents the window, in the example it would also capture the event since it is the only window that exists in the application.
But it can behave differently if you have several windows, which can be achieved with the iframe
tag, which creates a window object for each iframe you have, in this case it would only capture the event of the window you have selected.
For more information https://www.w3schools.com/html/html_iframe.asp .
Also clarify that window
is a global variable, which has document as a member, which is the root node