JavaScript

What did we learn the last time?

DOM - part 1

We have writing in the console. But now are we going to write on the site. But first I will tell something about the DOM.

DOM stands for Document Object Model and can define HTML elements as methods, gives them properties and events. The DOM can change the document structure, design and content.

When you open a website in the browser, parser the browser the HTML site. The browser builts the document structure and uses the DOM to draw on the screen.JavaScript uses the DOM to get acces to the document and its elements. The DOM is not a programming languange, but without it does JavaScript not know to websites og HTML documents. Every element in the document is a part of the Document Object Model

The DOM tree

For the DOM tree is every built HTML tag an object, what you can manipulate though JavaScript. The browser builts the tree when the site is loading. In the three is the lements defined as nodes which has the content of objects

JS DOM tree

Yellow

The yellow boxes are the root elements. They are on the top of the hiearki.
The document is alle websites, that will be loaded in the browser. Every element in the three is represented by a DOM node.
The DOM includes elements as the body tag or the h1 tag

Blue

The blue boxes are element nodes which describes the structure of an HTML site.

Pink

The pink boxes are attribute nodes which are HTML elements which contain attributes.

Green

The green boxes are text nodes which is the text outside an element.

Example on the DOM tree

<!doctype html> 
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<button id="JSbutton" style="background-color:white; outline:1px solid purple; border: none; padding: 10px;">What happens?</button>
</div>
<script src="../js/number.js"> </script>
</body>
</html>
Example 3.6.1
document.getElementById("JSbutton").addEventListener('click', function() { 
document.getElementById("JSbutton").style.backgroundColor = "red";
document.getElementById("JSbutton").style.color = "white";
});
Example 3.6.2

DOM nodes

Now we will talk about DOM nodes - The blue ones from the DOM tree

The document and it's properties

The document is an object, and each object can have some methods and properties attached.

document.title;
document.doctype;
document.head;
document.body;
document.all;
document.all[5];
Example 3.6.3

What do you get if you write it in the console?

Accessing the elements on the page

You can manipulate HTML elements on the site with DOM nodes.

This is a part from a the HTML site we will take as a starting point.

<main>
<section>
<img id="section-img" src="https://images.unsplash.com/photo-1542241647-9cbbada2b309?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1769&q=80" alt="Mountain from top taking by Jeff Hopper">
<h1 id="mainHeading">This is a heading</h1>
<p>Some text</p>
<ul>
<li>We can write on the site with the use of DOM nodes</li>
<li>We can change elements with the use of DOM nodes</li>
<li>We can make elements with the use of DOM nodes</li>
</ul>
</section>
</main>
Example 3.6.4

document.getElementById(id)

The easiest way to find an HTML element in the DOM, is by using the element id. If the element is found will the method return an element that you can manipulate. If it can not find the elements will it return null

const h1 = document.getElementById("mainHeading"); //get the element based on the id 
console.log(h1); //writes the element
Example 3.6.5

element.innerHTML

With the document.getElementById(id); we can grab the element, but we see what where are inside the element.

console.log(h1.innerHTML); //gives us the content
h1.innerHTML = "This is JavaScript DOM nodes"; //changes the content
Example 3.6.6

element.style

We can now change the content, but what about CSS?
You can also change that. To do it you can change the style instructions of the element, accessing the .style property.

h1.style.color = "darkblue"; //change the font color 
h1.style.backgroundColor = "lightgreen"; //change the background color
Example 3.6.7

document.getElementsByTagName(tag)

You can find elements with the tag name. The nodes can be accessed by index numbers

const li = document.getElementsByTagName("li"); //find all the elements with that tag
console.log(li); //writes alle the tags
console.log(li[0].innerHTML); //write the content of that one tag
Example 3.6.8

document.querySelector(selectors); method

If you do not want to use document.getElementById(); then use the .querySelector() method. By using the .querySelector() method, we cannot only access the elements that has id attribute, but practically every element on the page.

const image = document.querySelector("#section-img"); //gets the image
console.log(image); //write it in the console
Example 3.6.9

element.[attribut]

You can also change the attribute with the the attribute property

image.src = "https://images.unsplash.com/photo-1458966480358-a0ac42de0a7a?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1770&q=80";
Example 3.6.10

document.createElement(element)

This method creates an element with the specified name, and returns the element.

const btn = document.createElement("button"); //create element
Example 3.6.11

Can you see the button on the page?
Can you see it with help from JavaScript?

console.log(btn); //find the element with JS
btn.innerHTML = "CLICK ME"; //gives it some text inside 
console.log(btn); //find the element with JS
Example 3.6.12

document.setAttribute(attribute, value)

This method creates an attribute with the specified name, and gives it the specified value.

let btnClass = btn.setAttribute("id", "button");
Example 3.6.13

node.append(node)

This method adds a node to the specified parent node.

document.body.append(btn);
Example 3.6.14

target.addEventListener(type, function)

The EventTarget sets up a function that will be called when the specified event is delivered to the target.

document.getElementById("button").addEventListener('click', function() { 
console.log("you pressed the button");
});
Example 3.6.15

Dom nodes - Part 2

There are more DOM nodes

Accessing the elements on the page

You can manipulate HTML elements on the site with DOM nodes.

<section class="section-form"> 
<form id="form" action="#" method="post">
<label>Name:
<input type="text" id="name">
</label>
<br>
<button type="submit" value="submit">Send</button>
</form>
<p id="formText"></p>
</section>
Example 3.6.16

document.getElementsByClassName(classname)

If you want to find all elements with the class name you can use this method.

const sectionForm = document.getElementsByClassName("section-form"); //get the element 
sectionForm[0].style.backgroundColor = "pink"; //change the background color
Example 3.6.17

target.value

If you have an input field and want the information from the input field can you use value property.

const form = document.getElementById('form'); //get the form element 
const formText = document.getElementById('formText'); //get the paragraph, so we can change the value
const name = document.getElementById("name"); //get the inputfield

function submitPushed(event) { //make a function
formText.innerHTML = `${name.value}, you pushed the form`; ///change the value inside the div
event.preventDefault(); //tells the form is invalid
}

form.addEventListener('submit', submitPushed); //Adds a eventlistener
Example 3.6.18

A little help

To save keywords can you write this as the first on the document

// save keystrokes for id
const $ = function (foo) {
return document.getElementById(foo);
}
// save keystrokes for tagName
const tag$ = function (foo) {
return document.getElementsByTagName(foo);
}
// save keystrokes for className
const class$ = function (foo) {
return document.getElementsByClassName(foo);
}
Example 3.6.19

Examples

//without the ID function
document.getElementById("JSbutton").style.backgroundColor = "red";

//with the ID function
$("JSbutton").style.backgroundColor = "red";

//without the tagName function
let tagName = document.getElementsByTagName("li");

//with the tagName function
let tagName = tag$("li");

//without the ClassName function
let className = document.getElmenetsByClassName("className");

//with the classNamefunction
let className = class$("className");
Example 3.6.20

How can we use JavaScript?

Go up button

'use strict';
const body = document.getElementsByTagName("body")[0];
const button = document.createElement('button');
const textnode = document.createTextNode('To the top');
button.setAttribute("id", "topBtn");
button.append(textnode);
body.append(button);

// When the user scrolls down 20px from the top of the document, show the button
document.addEventListener('scroll', function(e){
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
button.style.display = "block";
} else {
button.style.display = "none";
}
};

// When the user clicks on the button, scroll to the top of the document
button.addEventListener("click", function() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
});
Example 3.6.21

Images

See the Pen Images by Dominoeffekten (@dominoeffekten) on CodePen.

<img id="bannerImage" src="https://images.unsplash.com/photo-1496387314164-18b0105f7553?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1951&q=80">
img{ 
width: 70%;
}
'use strict';
var images = [
"https://images.unsplash.com/photo-1500349812227-3264f5f54181?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1963&q=80",
"https://images.unsplash.com/photo-1437622368342-7a3d73a34c8f?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1920&q=80",
"https://images.unsplash.com/photo-1551946581-f7a62cd2f00b?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1950&q=80"
];
var text = ["butterfly", "fish", "frog"]
var i = 0;

var renew = setInterval(function(){
if(images.length == i){
i = 0;
} else {
document.getElementById("bannerImage").src = images[i];
document.getElementById("bannerImage").setAttribute("title", text[i]);
document.getElementById("bannerImage").setAttribute("alt", text[i]);
i++;
}
},3000);
Example 3.6.22

Modal box

See the Pen ModalBox by Dominoeffekten (@dominoeffekten) on CodePen.


<section id="container" class="baconIpsum">
<h2>Bacon Ipsum</h2>
<p>Bacon ipsum dolor amet t-bone pancetta tongue hamburger, bacon spare ribs burgdoggen short ribs filet mignon chislic picanha turducken.</p>
</section>
<button id="next">Next</button>

<section id="modalBox" class="zombieIpsum">
<span id="close">X</span>
<h2>Zombie ipsum</h2>
<p>Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis.</p>
</section>
.zombieIpsum{
display: none;
position: absolute;
top:0;
background-color: coral;
height:200px;
width:auto;
margin: 20px;
}

#close{
font-size:20px;
cursor: pointer;
}
//get the modal element
let modal = document.getElementById("modalBox");
//get the container elemenet
let container = document.getElementById("container");
// Get the element that closes the modal
var close = document.getElementById("close");

// When the user clicks the button, open the modal
function openModal(){
modal.style.display = "block";
}

// close the modalbox
function closeModal(event){
modal.style.display = "none";
}

document.getElementById("next").addEventListener("click", openModal);
close.addEventListener("click", closeModal);
Example 3.6.22