# Lesson 8 JavaScript and the DOM
# JavaScript and The DOM
The DOM Video
- Video Link Intro to The Document Object Model
- Length: 6:10 minutes
- Size: 35.0 MB
# JavaScript
JavaScript (JS) is a programming language best known as the scripting language for Web pages. JavaScript can also run outside browsers on desktops and servers using Node.js
The standard for JavaScript is ECMAScript. As of 2012, all modern browsers fully support ECMAScript 5.1. Older browsers support at least ECMAScript 3. On June 17, 2015, ECMA International published the sixth major version of ECMAScript, which is officially called ECMAScript 2015, and was initially referred to as ECMAScript 6 or ES6. Since then, ECMAScript standards are on yearly release cycles.
We will be learning the JavaScript version knowns as ES6.
# The Document Object Model (DOM)
The DOM is the interface between your JavaScript (programming code) and your HTML + CSS.
The DOM is a document model loaded in the browser and representing the document (HTML + CSS) as a node tree, where each node represents part of the document (e.g. an element, text string, or comment)
Lets start with a diagram to explain. In JavaScript code we want to add the ability to select our HTML elements, read their contents, then make changes to them. Another way to explain the DOM is: The DOM programmatically describes your HTML and CSS page. The DOM represents the current state of the page, not the original file, this means that if code makes changes to the page, the DOM will reflect the current state instead, not the original file.
Lets walk through a demo to show javaScript and the DOM in action. Don't think that you need to understand the details of the code we are going to show. The purpose of this demo is to teach the concept of the DOM.
The code for this section can be found on github. Please download the code and try it out on your machine. https://github.com/mhintegrity/lesson08
- Open the index.html file in Chrome Browser.
- Press F12 to open the Developer tools.
- Select the tab Console.
- Type in
console.dir(document)
. - Expand the carrots of #document to explore the DOM for the HTML page.
- Locate the head element, expand it and locate the title element.
- Locate the body element, expand and find the children object, expand again and find 0: h1.
Now lets look at the JavaScript in this project.
- In VS Code open the index.html page and look at the head section.
- You will see an entry like this
<script defer src="main.js"></script>
- script element tag tells the browser that this is JavaScript code. The attribute src points to an external file that contains JavaScript code.
- the defer attribute tells the browser to wait till the HTML page and its DOM is loaded before loading and running the JavaScript file.
- You can put your JavaScript code inside a script element, but we will be following the better practice of storing it in a separate file.
- Now open the main.js file in VS Code to look at.
- If you run the page and click on the button text "Hide the DOM image", you will see the image disappear and the text of the button change to "Show the DOM image".
- Now lets examine the JavaScript code that makes this happen.
- The first line starts with // which indicates that this line is a comment only and not code.
// Main JavaScript file used by index.html file //
- Next line of code creates a variable (like in math where x holds stuff for us) named getButton
let getButton = document.querySelector('#hide');
- document is a reference to the page DOM
- The period after document followed by querySelector is a reference to a function that document has. A function is like in math code/formulas that need to be run when referenced.
- So document.querySelector() is code which acts similar to a selector part of a rule in CSS.
- After a function name we use () parenthesis to contain any parameters (information the function need to work) we want to pass into the function.
- document.querySelector('#hide'); works like a CSS rule, but returns only the first element (a button) with an id of hide from the DOM.
- The next code line adds a listener to the button so that when the user clicks on the button, the function hideImage is called (run)
getButton.addEventListener('click', hideImage.bind());
- The bottom section is a custom function that we write.
function hideImage(event) { if (document.getElementById('hide').innerText === 'Hide the DOM image') { // Print a message inside the developer console. console.log("test Hide Image") // Like CSS we want to apply the display: none to our Image. document.getElementById('DOM').style.display = 'none'; document.getElementById('hide').innerText = 'Show the DOM image' } else { document.getElementById('DOM').style.display = 'block'; document.getElementById('hide').innerText = 'Hide the DOM image' } }
- We are not going to go into a lengthy explanation of this code yet, the purpose of this exercise is to show you the types of things we can do with JavaScript.
# Intro to JavaScript
JavaScript Variables
- Video Link Intro to JavaScript Variables
- Length: 6:10 minutes
- Size: 35.0 MB
# JavaScript Code
A computer program is a list of instruction that are executed in order. Program instructions are called statements.
JavaScript statements are separated by semicolons ;
add a semicolon at the end of each executable statement:
let x, y, z; // Decalare 3 variables x = 3; // Assign the number 3 to variable x y = 4; // Assign the number 4 to variable y z = 3 + 4; // Assign the sum of x and y to z;
Variables are memory containers used for storing data values Variables are much like variables in Algebra, except that they can contain data other than numbers.
5 Primitive Data Types used in value variables
// Numbers 6.6 -9 // Strings "Hello" 'What is your name' // Booleans true false // null and undefined null undefined
Like Algebra we can choose names for our variables;
let namesShouldHaveMeaning = "Hello"; let jesusIsLord = true;
Value = undefined
- Variables are often initially declared without values. Until a variable has a value, it will have a value of undefined.
- If you try to declare again the same variable you will get an error.
JavaScript algebra using operators and variables.
let a = 4 + 3; let composeStr = "add strings" + " 4 + 3 = " + a; // "add string 4 + 3 = 7"
# JavaScript Arithmetic Operators
Arithmetic operators are used to perform algebra on number data types
Operator | Description | Example |
+ | Addition | x = x + y; |
- | Subtraction | x = x - y; |
* | Multiplication | x = x * y; |
/ | Division | x = x / y; |
% | Modulus - Division Remainder | x = x /y; |
++ | Increment by 1 | x++; |
-- | Decrement by 1 | x--; |
# JavaScript Assignment Operators
Assignment operators assign values to JavaScript variables.
Operator | Example | Same As |
= | x = y; | x = y; |
+= | x += y; | x = x + y; |
-= | x -= y; | x = x - y; |
*= | x *= y; | x = x * y; |
/= | x /= y; | x = x / y; |
%= | x %= y; | x = x % y; |
# JavaScript Comparison Operators
- Comparison operators are used when comparing variables. For example we use it with IF statements.
Operator Description Example == equal to if (5 == 5) { }; === equal value and equal type if (a === b) { }; != not equal if (a != b) { }; !== not equal value or not equal type if (a !== b) { }; > greater than if (a > b) { }; < less than if (a < b) { }; >= greater than or equal to if (a >= b) { }; <= less than or equal to if (a <= b) { }; ? ternary operator
condition ? value if true : value if falsea = (5 >= 4) ? true : false;
# Assignment due for discussion next class and NO check-in to GitHub.
- Read and try the following on-line learning resource:
- https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Variables
- Please send questions you have in slack so that we can talk about it next class.