Javascript.info Ebook Part 2 Browser Document, Events, Interfaces (Ilya Kantor, javascript.info) (z-library.sk, 1lib.sk, z-lib.sk)
Author: Ilya Kantor, javascript.info
JavaScript
No Description
📄 File Format:
PDF
💾 File Size:
4.2 MB
13
Views
0
Downloads
0.00
Total Donations
📄 Text Preview (First 20 pages)
ℹ️
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
📄 Page
1
Browser: Document, Events, Interfaces Part 2 Ilya Kantor
📄 Page
2
● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● Built at July 10, 2019 The last version of the tutorial is at https://javascript.info. We constantly work to improve the tutorial. If you find any mistakes, please write at our github. Document Browser environment, specs DOM tree Walking the DOM Searching: getElement*, querySelector* Node properties: type, tag and contents Attributes and properties Modifying the document Styles and classes Element size and scrolling Window sizes and scrolling Coordinates Introduction to Events Introduction to browser events Bubbling and capturing Event delegation Browser default actions Dispatching custom events UI Events Mouse events basics Moving: mouseover/out, mouseenter/leave Drag'n'Drop with mouse events Keyboard: keydown and keyup Scrolling Forms, controls Form properties and methods Focusing: focus/blur Events: change, input, cut, copy, paste Forms: event and method submit Document and resource loading Page: DOMContentLoaded, load, beforeunload, unload
📄 Page
3
● ● ● ● ● ● Scripts: async, defer Resource loading: onload and onerror Miscellaneous Mutation observer Selection and Range Event loop: microtasks and macrotasks
📄 Page
4
Learning how to manage the browser page: add elements, manipulate their size and position, dynamically create interfaces and interact with the visitor. Here we’ll learn to manipulate a web-page using JavaScript. The JavaScript language was initially created for web browsers. Since then, it has evolved and become a language with many uses and platforms. A platform may be a browser, or a web-server, or a washing machine, or another host. Each of them provides platform-specific functionality. The JavaScript specification calls that a host environment. A host environment provides platform-specific objects and functions additional to the language core. Web browsers give a means to control web pages. Node.js provides server-side features, and so on. Here’s a bird’s-eye view of what we have when JavaScript runs in a web-browser: There’s a “root” object called window . It has two roles: 1. First, it is a global object for JavaScript code, as described in the chapter Global object. 2. Second, it represents the “browser window” and provides methods to control it. For instance, here we use it as a global object: Document Browser environment, specs function sayHi() { alert("Hello");
📄 Page
5
● And here we use it as a browser window, to see the window height: There are more window-specific methods and properties, we’ll cover them later. The document object gives access to the page content. We can change or create anything on the page using it. For instance: Here we used document.body.style , but there’s much, much more. Properties and methods are described in the specification: DOM Living Standard at https://dom.spec.whatwg.org DOM is not only for browsers The DOM specification explains the structure of a document and provides objects to manipulate it. There are non-browser instruments that use it too. For instance, server-side tools that download HTML pages and process them use the DOM. They may support only a part of the specification though. } // global functions are accessible as properties of window window.sayHi(); alert(window.innerHeight); // inner window height DOM (Document Object Model) // change the background color to red document.body.style.background = "red"; // change it back after 1 second setTimeout(() => document.body.style.background = "", 1000);
📄 Page
6
● ● CSSOM for styling CSS rules and stylesheets are not structured like HTML. There’s a separate specification CSSOM that explains how they are represented as objects, and how to read and write them. CSSOM is used together with DOM when we modify style rules for the document. In practice though, CSSOM is rarely required, because usually CSS rules are static. We rarely need to add/remove CSS rules from JavaScript, so we won’t cover it right now. Browser Object Model (BOM) are additional objects provided by the browser (host environment) to work with everything except the document. For instance: The navigator object provides background information about the browser and the operating system. There are many properties, but the two most widely known are: navigator.userAgent – about the current browser, and navigator.platform – about the platform (can help to differ between Windows/Linux/Mac etc). The location object allows us to read the current URL and can redirect the browser to a new one. Here’s how we can use the location object: Functions alert/confirm/prompt are also a part of BOM: they are directly not related to the document, but represent pure browser methods of communicating with the user. BOM is the part of the general HTML specification . Yes, you heard that right. The HTML spec at https://html.spec.whatwg.org is not only about the “HTML language” (tags, attributes), but also covers a bunch of objects, methods and browser-specific DOM extensions. That’s “HTML in broad BOM (Browser object model) alert(location.href); // shows current URL if (confirm("Go to wikipedia?")) { location.href = "https://wikipedia.org"; // redirect the browser to another URL }
📄 Page
7
terms”. Also, some parts have additional specs listed at https://spec.whatwg.org . Talking about standards, we have: DOM specification Describes the document structure, manipulations and events, see https://dom.spec.whatwg.org . CSSOM specification Describes stylesheets and style rules, manipulations with them and their binding to documents, see https://www.w3.org/TR/cssom-1/ . HTML specification Describes the HTML language (e.g. tags) and also the BOM (browser object model) – various browser functions: setTimeout , alert , location and so on, see https://html.spec.whatwg.org . It takes the DOM specification and extends it with many additional properties and methods. Additionally, some classes are described separately at https://spec.whatwg.org/ . Please note these links, as there’s so much stuff to learn it’s impossible to cover and remember everything. When you’d like to read about a property or a method, the Mozilla manual at https://developer.mozilla.org/en-US/search is also a nice resource, but the corresponding spec may be better: it’s more complex and longer to read, but will make your fundamental knowledge sound and complete. To find something, it’s often convenient to use an internet search “WHATWG [term]” or “MDN [term]”, e.g https://google.com?q=whatwg+localstorage , https://google.com?q=mdn+localstorage . Now we’ll get down to learning DOM, because the document plays the central role in the UI. The backbone of an HTML document are tags. Summary DOM tree
📄 Page
8
According to Document Object Model (DOM), every HTML-tag is an object. Nested tags are called “children” of the enclosing one. The text inside a tag it is an object as well. All these objects are accessible using JavaScript. For instance, let’s explore the DOM for this document: The DOM represents HTML as a tree structure of tags. Here’s how it looks: ▾ HTML ▾ HEAD #text ↵␣␣␣␣ ▾ TITLE #text About elks #text ↵␣␣ #text ↵␣␣ ▾ BODY #text The truth about elks. Tags are called element nodes (or just elements). Nested tags become children of the enclosing ones. As a result we have a tree of elements: <html> is at the root, then <head> and <body> are its children, etc. The text inside elements forms text nodes, labelled as #text . A text node contains only a string. It may not have children and is always a leaf of the tree. For instance, the <title> tag has the text "About elks" . An example of DOM <!DOCTYPE HTML> <html> <head> <title>About elks</title> </head> <body> The truth about elks. </body> </html>
📄 Page
9
● ● Please note the special characters in text nodes: a newline: ↵ (in JavaScript known as \n ) a space: ␣ Spaces and newlines – are totally valid characters, they form text nodes and become a part of the DOM. So, for instance, in the example above the <head> tag contains some spaces before <title> , and that text becomes a #text node (it contains a newline and some spaces only). There are only two top-level exclusions: 1. Spaces and newlines before <head> are ignored for historical reasons, 2. If we put something after </body> , then that is automatically moved inside the body , at the end, as the HTML spec requires that all content must be inside <body> . So there may be no spaces after </body> . In other cases everything’s straightforward – if there are spaces (just like any character) in the document, then they become text nodes in DOM, and if we remove them, then there won’t be any. Here are no space-only text nodes: ▾ HTML ▾ HEAD ▾ TITLE #text About elks ▾ BODY #text The truth about elks. <!DOCTYPE HTML> <html><head><title>About elks</title></head><body>The truth about elks.</body></h
📄 Page
10
Edge spaces and in-between empty text are usually hidden in tools Browser tools (to be covered soon) that work with DOM usually do not show spaces at the start/end of the text and empty text nodes (line-breaks) between tags. That’s because they are mainly used to decorate HTML, and do not affect how it is shown (in most cases). On further DOM pictures we’ll sometimes omit them where they are irrelevant, to keep things short. If the browser encounters malformed HTML, it automatically corrects it when making DOM. For instance, the top tag is always <html> . Even if it doesn’t exist in the document – it will exist in the DOM, the browser will create it. The same goes for <body> . As an example, if the HTML file is a single word "Hello" , the browser will wrap it into <html> and <body> , add the required <head> , and the DOM will be: ▾ HTML ▾ HEAD ▾ BODY #text Hello While generating the DOM, browsers automatically process errors in the document, close tags and so on. Such an document with unclosed tags: …Will become a normal DOM, as the browser reads tags and restores the missing parts: Autocorrection <p>Hello <li>Mom <li>and <li>Dad
📄 Page
11
▾ HTML ▾ HEAD ▾ BODY ▾ P #text Hello ▾ LI #text Mom ▾ LI #text and ▾ LI #text Dad ⚠ Tables always have <tbody> An interesting “special case” is tables. By the DOM specification they must have <tbody> , but HTML text may (officially) omit it. Then the browser creates <tbody> in DOM automatically. For the HTML: DOM-structure will be: ▾ TABLE ▾ TBODY ▾ TR ▾ TD #text 1 You see? The <tbody> appeared out of nowhere. You should keep this in mind while working with tables to avoid surprises. <table id="table"><tr><td>1</td></tr></table> Other node types
📄 Page
12
Let’s add more tags and a comment to the page: ▾ HTML ▾ HEAD ▾ BODY #text The truth about elks. ▾ OL #text ↵␣␣␣␣␣␣ ▾ LI #text An elk is a smart #text ↵␣␣␣␣␣␣ #comment comment #text ↵␣␣␣␣␣␣ ▾ LI #text ...and cunning animal! #text ↵␣␣␣␣ #text ↵␣␣↵ Here we see a new tree node type – comment node, labeled as #comment . We may think – why is a comment added to the DOM? It doesn’t affect the visual representation in any way. But there’s a rule – if something’s in HTML, then it also must be in the DOM tree. Everything in HTML, even comments, becomes a part of the DOM. <!DOCTYPE HTML> <html> <body> The truth about elks. <ol> <li>An elk is a smart</li> <!-- comment --> <li>...and cunning animal!</li> </ol> </body> </html>
📄 Page
13
Even the <!DOCTYPE...> directive at the very beginning of HTML is also a DOM node. It’s in the DOM tree right before <html> . We are not going to touch that node, we even don’t draw it on diagrams for that reason, but it’s there. The document object that represents the whole document is, formally, a DOM node as well. There are 12 node types . In practice we usually work with 4 of them: 1. document – the “entry point” into DOM. 2. element nodes – HTML-tags, the tree building blocks. 3. text nodes – contain text. 4. comments – sometimes we can put the information there, it won’t be shown, but JS can read it from the DOM. To see the DOM structure in real-time, try Live DOM Viewer . Just type in the document, and it will show up DOM at an instant. Another way to explore the DOM is to use the browser developer tools. Actually, that’s what we use when developing. To do so, open the web-page elks.html, turn on the browser developer tools and switch to the Elements tab. It should look like this: See it for yourself In the browser inspector
📄 Page
14
You can see the DOM, click on elements, see their details and so on. Please note that the DOM structure in developer tools is simplified. Text nodes are shown just as text. And there are no “blank” (space only) text nodes at all. That’s fine, because most of the time we are interested in element nodes. Clicking the button in the left-upper corner allows to choose a node from the webpage using a mouse (or other pointer devices) and “inspect” it (scroll to it in the Elements tab). This works great when we have a huge HTML page (and corresponding huge DOM) and would like to see the place of a particular element in it. Another way to do it would be just right-clicking on a webpage and selecting “Inspect” in the context menu.
📄 Page
15
● ● ● ● ● ● At the right part of the tools there are the following subtabs: Styles – we can see CSS applied to the current element rule by rule, including built-in rules (gray). Almost everything can be edited in-place, including the dimensions/margins/paddings of the box below. Computed – to see CSS applied to the element by property: for each property we can see a rule that gives it (including CSS inheritance and such). Event Listeners – to see event listeners attached to DOM elements (we’ll cover them in the next part of the tutorial). …and so on. The best way to study them is to click around. Most values are editable in-place. As we explore the DOM, we also may want to apply JavaScript to it. Like: get a node and run some code to modify it, to see the result. Here are few tips to travel between the Elements tab and the console. Select the first <li> in the Elements tab. Press Esc – it will open console right below the Elements tab. Now the last selected element is available as $0 , the previously selected is $1 etc. Interaction with console
📄 Page
16
We can run commands on them. For instance, $0.style.background = 'red' makes the selected list item red, like this: From the other side, if we’re in console and have a variable referencing a DOM node, then we can use the command inspect(node) to see it in the Elements pane. Or we can just output it in the console and explore “at-place”, like document.body below:
📄 Page
17
● ● ● That’s for debugging purposes of course. From the next chapter on we’ll access and modify DOM using JavaScript. The browser developer tools are a great help in development: we can explore the DOM, try things and see what goes wrong. An HTML/XML document is represented inside the browser as the DOM tree. Tags become element nodes and form the structure. Text becomes text nodes. …etc, everything in HTML has its place in DOM, even comments. We can use developer tools to inspect DOM and modify it manually. Here we covered the basics, the most used and important actions to start with. There’s an extensive documentation about Chrome Developer Tools at https://developers.google.com/web/tools/chrome-devtools . The best way to learn the tools is to click here and there, read menus: most options are obvious. Later, when you know them in general, read the docs and pick up the rest. Summary
📄 Page
18
DOM nodes have properties and methods that allow to travel between them, modify, move around the page and more. We’ll get down to them in the next chapters. The DOM allows us to do anything with elements and their contents, but first we need to reach the corresponding DOM object. All operations on the DOM start with the document object. From it we can access any node. Here’s a picture of links that allow for travel between DOM nodes: Let’s discuss them in more detail. The topmost tree nodes are available directly as document properties: <html> = document.documentElement The topmost document node is document.documentElement . That’s DOM node of <html> tag. <body> = document.body Another widely used DOM node is the <body> element – document.body . Walking the DOM On top: documentElement and body
📄 Page
19
● ● <head> = document.head The <head> tag is available as document.head . ⚠ There’s a catch: document.body can be null A script cannot access an element that doesn’t exist at the moment of running. In particular, if a script is inside <head> , then document.body is unavailable, because the browser did not read it yet. So, in the example below the first alert shows null : In the DOM world null means “doesn’t exist” In the DOM, the null value means “doesn’t exist” or “no such node”. There are two terms that we’ll use from now on: Child nodes (or children) – elements that are direct children. In other words, they are nested exactly in the given one. For instance, <head> and <body> are children of <html> element. Descendants – all elements that are nested in the given one, including children, their children and so on. <html> <head> <script> alert( "From HEAD: " + document.body ); // null, there's no <body> yet </script> </head> <body> <script> alert( "From BODY: " + document.body ); // HTMLBodyElement, now it exists </script> </body> </html> Children: childNodes, firstChild, lastChild
📄 Page
20
For instance, here <body> has children <div> and <ul> (and few blank text nodes): …And all descendants of <body> are not only direct children <div> , <ul> but also more deeply nested elements, such as <li> (a child of <ul> ) and <b> (a child of <li> ) – the entire subtree. The childNodes collection provides access to all child nodes, including text nodes. The example below shows children of document.body : Please note an interesting detail here. If we run the example above, the last element shown is <script> . In fact, the document has more stuff below, but at <html> <body> <div>Begin</div> <ul> <li> <b>Information</b> </li> </ul> </body> </html> <html> <body> <div>Begin</div> <ul> <li>Information</li> </ul> <div>End</div> <script> for (let i = 0; i < document.body.childNodes.length; i++) { alert( document.body.childNodes[i] ); // Text, DIV, Text, UL, ..., SCRIPT } </script> ...more stuff... </body> </html>
The above is a preview of the first 20 pages. Register to read the complete e-book.
Recommended for You
Loading recommended books...
Failed to load, please try again later