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); } });
All global JavaScript objects, functions, and variables automatically become members of the window object. Global variables are properties of the window object. Global functions are methods of the window object. Even the document object (of the HTML DOM) is a property of the window object: window.
document is the actual object for your html page loaded in browser. This is a DOM object. Document is the function(a DOM interface precisely), which will be used to create the document object. This "Document" is implemented by the browser program.
They refer to the same element, the difference is that when you say document. body you are passing the element directly to jQuery. Alternatively, when you pass the string 'body' , the jQuery selector engine has to interpret the string to figure out what element(s) it refers to.
$(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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With