JavaScript is one of the most popular skills in today’s job market. It allows you to create both client- and server-side applications quickly and easily. Having a solid understanding of this powerful and versatile language is essential to anyone who uses it.
“Practical JavaScript Programming” does not only focus on best practices, but also introduces the fundamental concepts. This course will take you from JavaScript basics to advanced. You’ll learn about topics like Data Types, Functions, Events, AJAX and more.
3. 3
Wilson Su
Front-end Developer, HIE
● 6 years in web design
● Specialize in JavaScript /
CSS / HTML / OOP / Git
● Familiar with PHP / Design
Pattern
● Interested in UI & Ix Design
wilson_su@trend.com.tw
4. Outline
4
Practical JavaScript Programming
Chapter 7.
● What Is the DOM?
● DOM Manipulation
● Performance Optimization
HTML DOM
Chapter 8.
DOM Events
● Callback Function
● On-event Handlers
● Event Listener Registration
● Event Capturing and Bubbling
● Event Delegation
7. Document Object Model
7
The Document Object Model is an application programming interface that
treats an HTML or XML document as a tree structure wherein each node is
an object representing a part of the document. – Wiki
What Is the DOM?
8. The HTML DOM Defines
– the HTML elements as objects
– the properties of all HTML elements
– the methods to access all HTML elements
– the events for all HTML elements
8
What Is the DOM?
10. 10
html
HTML DOM Tree
What Is the DOM?
head body
metatitle header
#document
nav main footer
Root element
h1
#text
11. HTML DOM Node Types
11
What Is the DOM?
body
a img
#text
href src #comment
#document
html
9 Document
1 Element
2 Attribute
3 Text
8 Comment
12. Node VS Element
12
What Is the DOM?
Node
Element
A node is the generic name for any type of
object in the DOM.
Ex. document node, text node, comment
node, attribute node, etc.
An element is one specific type of node.
Ex. body element, div element, table
element, input element, etc.
13. DOM VS BOM
13
What Is the DOM?
● Document Object Model
● Manipulate the HTML document
● Standard specifications
recommended by the W3C
● Browser Object Model
● Access and manipulate the
browser window
● No standards! Each browser has
its own implementation
DOM BOM
32. Inserting A Node
32
DOM Manipulation
Sed posuere consectetur
est at lobortis.
1. before
2. prepend
3. append
4. after
target.parentNode.insertBefore(elem, target);
target.insertBefore(elem, target.firstChild);
target.appendChild(elem);
target.parentNode.insertBefore(elem, target.nextSibling);
target
33. Inserting HTML
33
DOM Manipulation
Sed posuere consectetur
est at lobortis.
1. before
2. prepend
3. append
4. after
target.insertAdjacentHTML('beforebegin', html);
target.insertAdjacentHTML('afterbegin', html);
target.insertAdjacentHTML('beforeend', html);
target.insertAdjacentHTML('afterend', html);
target
38. Food truck fixie locavore,
accusamus mcsweeney's marfa
nulla single-origin coffee squid.
Exercitation +1 labore velit, blog
sartorial PBR leggings next level
wes anderson artisan four loko
farm-to-table craft beer twee. Qui
photo booth letterpress, commodo
enim craft beer mlkshk aliquip
jean shorts ullamco ad vinyl cillum
PBR. Homo nostrud organic,
assumenda labore aesthetic magna
delectus mollit. Keytar helvetica
VHS salvia yr, vero magna velit
sapiente labore stumptown.
What is offsetHeight, clientHeight, scrollHeight?
38
DOM Manipulation
Offset
Height
Client
Height
Scroll
Height
border scrollbar
41. Finding Elements in a Bad Way
41
1. ['Add', 'Update', 'Remove'].forEach(function (action) {
2. var toolbar = document.getElementById('toolbar');
3. var button = document.createElement('button');
4. var text = document.createTextNode(action);
5.
6. button.appendChild(text);
7. toolbar.appendChild(button);
8. });
42. Finding Elements in a Good Way
42
1. var toolbar = document.getElementById('toolbar');
2.
3. ['Add', 'Update', 'Remove'].forEach(function (action) {
4. var button = document.createElement('button');
5. var text = document.createTextNode(action);
6.
7. button.appendChild(text);
8. toolbar.appendChild(button);
9. });
44. Appending Child Nodes in a Bad Way
44
1. var list = document.getElementById('list');
2.
3. ['Iris', 'Frank', 'Sofia'].forEach(function (user) {
4. var item = document.createElement('li');
5. var text = document.createTextNode(user);
6.
7. item.appendChild(text);
8. list.appendChild(item);
9. });
45. Appending Child Nodes in a Good Way
45
1. var list = document.getElementById('list');
2. var fragment = document.createDocumentFragment();
3. var item, text;
4.
5. ['Iris', 'Frank', 'Sofia'].forEach(function (user) {
6. item = document.createElement('li');
7. text = document.createTextNode(user);
8. item.appendChild(text);
9. fragment.appendChild(item);
10. });
11.
12. list.appendChild(fragment);
46. Batch your DOM changes,
especially when updating styles.
46
47. Update Element Styles in a Bad Way
47
1. var box = document.getElementById('box');
2.
3. box.style.background = 'white';
4. box.style.border = '1px solid blue';
5. box.style.color = 'red';
48. Update Element Styles in a Good Way
48
1. var box = document.getElementById('box');
2.
3. box.style.cssText = ''.concat(
4. 'background: white;',
5. 'border: 1px solid blue;',
6. 'color: red;'
7. );
49. Update Element Styles in a Better Way
49
1. <style>
2. .box-highlight {
3. background: white;
4. border: 1px solid blue;
5. color: red;
6. }
7. </style>
8. <script>
9. var box = document.getElementById('box');
10. box.classList.add('box-highlight');
11. </script>
54. HTML DOM Events
● Every HTML element contains a set of events
● HTML allows event handler attributes, with JavaScript code
● Developers can use event handlers to detect and react to events
54
DOM Events
55. Examples Of DOM Events
● A web page has finished loading
● A browser window has resized
● A media is playing
● A text input field was changed
● A button was clicked
55
DOM Events
57. What is a Callback Function?
57
A callback function is a function passed into another function as an
argument, which is then invoked inside the outer function to complete
some kind of routine or action. – MDN
Callback Function
71. DOMContentLoaded Event VS load Event
71
The DOMContentLoaded event is fired when the initial HTML document
has been completely loaded and parsed. A very different event load
should be used only to detect a fully-loaded page, which means it has
finished loading all files, including subframes and images.
Event Listener Registration
72. Finding Elements Before DOM is Ready
1. <head>
2. <script>
3. console.log(document.getElementById('main')); // null
4. </script>
5. </head>
6. <body>
7. <div id="main"></div>
8. </body>
72
73. Finding Elements After DOM is Ready
73
1. <body>
2. <div id="main"></div>
3. <script>
4. console.log(document.getElementById('main'));
5. // [object HTMLDivElement]
6. </script>
7. </body>
74. Finding Elements After DOM is Ready
74
1. <head>
2. <script>
3. var event = 'DOMContentLoaded';
4. document.addEventListener(event, function () {
5. console.log(document.getElementById('main'));
6. // [object HTMLDivElement]
7. });
8. </script>
9. </head>
10. <body>
11. <div id="main"></div>
12. </body>
75. RENDER PROCESS
NETWORK
When Your Code Will Run
75
Event Listener Registration
Page Load
DOMContentLoaded
Event
load
Event
Get
JS
Get
CSS
Build
DOM
Get
HTML
Run
JS
Build
CSSOM
BlockedIdle
Request
Page
Render
Code waiting for the DOMContentLoaded event
Code waiting for the load event
1
2
3
4
5
6 7 8
80. Prevents the Event from Bubbling up the DOM Tree
80
1. var save = document.querySelector('#save');
2.
3. document.body.addEventListener('click', function (e) {
4. /* This event handler won’t be executed. */
5. });
6.
7. save.addEventListener('click', function (e) {
8. e.stopPropagation();
9. });
81. Keeps the Rest of the Handlers from Being Executed
81
1. var save = document.querySelector('#save');
2.
3. document.body.addEventListener('click', function (e) {
4. /* This event handler won’t be executed. */
5. });
6.
7. save.addEventListener('click', function (e) {
8. e.stopImmediatePropagation();
9. });
10.
11. save.addEventListener('click', function (e) {
12. /* This event handler won’t be executed either. */
13. });
82. Canceling the Default Action of Elements
82
1. <input id="checkbox" type="checkbox"/>
2. <a id="link" href="https://google.com">Google</a>
3. <script>
4. function preventDefault (e) {
5. e.preventDefault();
6. }
7. var checkbox = document.querySelector('#checkbox');
8. var link = document.querySelector('#link');
9.
10. checkbox.addEventListener('click', preventDefault);
11. link.addEventListener('click', preventDefault);
12. </script>
84. Registering Event Listeners in a Bad Way
84
1. var list = document.getElementById('list');
2. var items = list.querySelectorAll('li');
3. var length = items.length, i = 0;
4.
5. while (i < length) {
6. items[i].addEventListener('click', function (e) {
7. e.target.style.color = 'red';
8. });
9. ++i;
10. }
85. Attaching a Delegated Event Handler to a Parent Element
85
1. function delegator (elem) {
2. return function (type, selector, fn) {
3. var listener = function (e) {
4. e.target.matches(selector) && fn.call(e.target, e);
5. };
6. elem.addEventListener(type, listener);
7. return listener;
8. };
9. }
10. var list = document.getElementById('list');
11. delegator(list)('click', 'li', function (e) { … });
12. delegator(list)('click', 'li.active', function (e) { … });
90. Reference
90
● Callback (computer programming) - Wikipedia
● Document Object Model - Wikipedia
● Handling Events :: Eloquent JavaScript
● JavaScript and HTML DOM Reference - W3Schools
● JavaScript Events
● Running Your Code at the Right Time | KIRUPA
● Web API reference - Web technology reference | MDN
● Web performance potimization
Practical JavaScript Programming