JS V

Today

  • Adding and removing DOM nodes
  • Keyboard events

Recap from last class

  • Asynchronous JS (async and await)
  • Adding and removing DOM nodes

async and await

Instead of using then() method

async function getData() {
    const url = "colleges.json"
    const response  = await fetch(url);
    console.log(`Received response: ${response.status}`);

}

async and await

async function getData() {
    const url = "colleges.json"
    const response  = await fetch(url);
    console.log(`Received response: ${response.status}`);

}

async marks that it is an asynchronous function

async and await

async function getData() {
    const url = "colleges.json"
    const response  = await fetch(url);
    console.log(`Received response: ${response.status}`);

}

await will cause the function to ‘freeze’ till the Promise is resolved

async and await

const url = "colleges.json"
const fetchPromise = fetch(url);
fetchPromise
  .then((response) => response.json())
  .then((data) => {
    console.log(data[0].name);
  });

==

const getData = async () => {
    const url = "colleges.json"
    const response = await fetch(url);
    const data = await response.json()
    console.log(data[0].name)
}

async and await

const getJson = async (url) => {
    const response = await fetch(url);
    if (!response.ok) {
        throw new Error(`Error! ${response}`)
    }
    const data = await response.json()
    console.log(data[0].name)
    return data;
}
// Calling it from another `async` function
try {
    let colleges = await getJson("colleges.json");
} catch(error) {
    console.error(error);
}

Recap from last class

  • Asynchronous JS (async and await)
  • Adding and removing DOM nodes

We can add and remove nodes using JS

Adding a new node

3 steps

  • Create a node
  • Set values and attributes
  • Attach it to the DOM tree

Creating a node

createElement()

const newDiv = document.createElement("div");
const p = document.createElement("p");

String argument specifying the types of element

Creating a text node

createTextNode()

const newText = document.createTextNode("HCDD 340");

String argument for the text

Adding a new node

3 steps

  • Create a node
  • Set values and attributes
  • Attach it to the DOM tree

Setting attributes

setAttribute()


const p = document.createElement("p");
// set id
p.setAttribute("id", "new-id");

// setting css class
p.setAttribute("class", "large-text");

Two arguments: name and value

Setting class attribute

Multiple options (examples)

const div = document.createElement("div");

div.className = "foo";
// <div class="foo"></div>

// add 3 classes
div.classList.add("foo", "bar", "baz");

// removes two classes
div.classList.remove("foo", "bar");

// if visible is set remove it, otherwise add it
div.classList.toggle("visible");

Adding a new node

3 steps

  • Create a node
  • Set values and attributes
  • Attach it to the DOM tree

appendChild()

const sect = document.querySelector("section");
const para = document.createElement("p");

// add at the end of the section
sect.appendChild(para);

Appends a node to the parent

insertBefore()

<div id="parent">
  <span id="child">foo</span>
</div>
// Create a new, plain <span> element
const sp1 = document.createElement("span");

// Get the reference element
const sp2 = document.getElementById("child");
// Get the parent element
const parentDiv = sp2.parentNode;

// Insert the new element into before sp2
parentDiv.insertBefore(sp1, sp2);

The new node will be placed before a reference node

after()

let container = document.createElement("div");
let p = document.createElement("p");
container.appendChild(p);
let span = document.createElement("span");

p.after(span);

// "<div><p></p><span></span></div>"

Insert the node after a given node

after() for text node

let container = document.createElement("div");
let p = document.createElement("p");
container.appendChild(p);

p.after("Text");
// "<div><p></p>Text</div>"

“Strings are inserted as equivalent Text nodes”

Removing elements

removeChild()

<div id="parent">
  <div id="child"></div>
</div>
const parent = document.getElementById("parent");
const child = document.getElementById("child");
const throwawayNode = parent.removeChild(child);

Removes the child node from the parent

Removing elements

const node = document.getElementById("child");
node.parentNode.removeChild(node);

parentNode points to the parent

Today

  • Adding and removing DOM nodes
  • Keyboard events

Todo

  • Open Activity 17
  • Update main.js
    • Add nodes when a button is clicked
    • see output.html for the final outcome

Hints

Start with Overview section

  • Update addOverviewContent in main.js
  • 3 elements
    • Image
    • H2
    • Text
  • What’s the parent root for these elements?

Hints II

  • Update addHeaderContent in main.js
  • What are the components?

Hints III

Objective

  • Update addObjectiveContent in main.js
  • Two components
    • H2
    • list
  • What’s the parent element?
  • How would you add the new parent element?

Today

  • Adding and removing DOM nodes
  • Keyboard events

Keyboard events

  • To get text entered by your user, we usually rely on button clicks (e.g., “Submit”)
  • Button click indicates user is done with text entering
  • Then, we can extract the text
<input type="text" name="module" id="module">
<button id="btn_add">Add a module!</button>
const addModule = (event) => {
    const input = document.querySelector('input');
    const moduleName = input.value;

};

However, some use cases require handling keyboard events directly (e.g., games, shortcuts)

Keyboard events

  • Key is pressed — keydown event
  • Key is released — keyup event

target.addEventListener("keydown", (event) => { 
    /* Key pressed */
});

target.addEventListener("keyup", (event) => { 
    /* Key released */
});

Keyboard events

The event object contains key information

  • key: value of the key pressed
  • ctrlKey: was Ctrl key active?
  • shiftKey: was Shift key active?
  • metaKey: was the meta key active?
    • ⌘ in Mac, ⊞ in Windows

Todo

  • Open Activity 18
  • What happens if you press the “v” key?

Keyboard events

window.addEventListener("keydown", event => {
    if (event.key == "v") {
        document.body.style.background = "violet";
    }
});
window.addEventListener("keyup", event => {
    if (event.key == "v") {
        document.body.style.background = "";
    }
});

“Page turns violet when you hold the V key”

Which element is the event listener?

window.addEventListener("keydown", event => {
    if (event.key == "v") {
        document.body.style.background = "violet";
    }
});
window.addEventListener("keyup", event => {
    if (event.key == "v") {
        document.body.style.background = "";
    }
});

window contains the DOM document

window makes items globally available (functions, event handlers, objects)

Todo

  • Log the key values in both event handlers
  • What happens when you press
    • ‘Enter’, ‘Delete’, ‘Tab’?
    • ‘Shift’, ‘Ctrl’, ‘Meta’ key with another key?
  • What happens when you hold down a key?