I have the following JQuery function that takes user input and displays it on screen. When I select for both $(document)
and $(window)
the function works. What is the disadvantage to using either selector? Where can I read more on these selectors and their differences?
Thank you in advance.
$(document).keypress(function(e) {
if(e.keyCode == 13) {
var id = $("input#example").val()
console.log(id);
$('#data').append(id);
}
});
While using the window
or document
object in a jQuery dom selector, most of the time you won't notice a difference between the two.
However, it's important to note that they are not the same object.
window
- refers to the viewport. It's used as the main global object in JavaScript.
document
- a direct descendant of window
; refers to the root of the document tree.
All DOM elements are a descendant of the document
, which is a direct descendant of window
.
$(window)
selector is for selecting the viewport
$(document)
selector is for the entire document (that is, what's inside the <html>
tag, even if it exapnds beyond the viewport).
To answer this question let me begin with the definition of the DOM, what we commonly know as "document
".
The Document Object Model (DOM) is an application programming interface (API) for valid HTML and well-formed XML documents. It defines the logical structure of documents and the way a document
is accessed and manipulated. In the DOM specification, the term "document" is used in the broad sense.
Now let me explain a little of what I found about browsing context
s, as that is the relationship that a Document
and a Window
normally have—although it is important to mention that a Document
may exist without a browsing context
, but you should never see that with jquery.
A user interacts with the main view of the Document
. A view is defined as the media that is being used to present the Document
to the user agent—e.g. screen, print, speech. The main view is the default view and is represented by an AbstractView
object that implements the Window
interface.
And to put it really simple, window
is the container and document
is the content. But I do recommend to at least skim through the documentation of this to have a better understanding.
Sources:
- W3C - What is the
DOM,
- W3C - Browsing
contexts