GDI Logo

Intermediate JavaScript

Class 2

Agenda

  • Review Quiz
  • Objects
  • JSON
  • Working with the DOM

Review Quiz

Given the array "students", how would you access the last item?


            const last = students[students.length-1];
          

What will the last expression evaluate to?



let gold = 100;
 
gold >= 120 ? "Sword acquired" : "{Not enough gold}";
            

"{Not enough gold}"
             

What Array method adds a given element to the end of the array?


.push()


const games = ["XCOM","Mario Kart","Destiny"];
games.push("Anthem");
console.log(games); // ["XCOM","Mario Kart","Destiny","Anthem"]
              

Describe what the following function "x" does


let x = () => Math.random() > .6 ? "Heads" : "Tails";

let x = function(){
  return Math.random() > .6 ? "Heads" : "Tails";
}

let x = function(){
  const randNum = Math.random();
  if(randNum > .6){
    return "Heads";
  }else{
    return "Tails";
  }
}

Is this a "fair coin?" Why or why not?

Object

An object is a common data structure containing properties (variables) and methods (functions)


const objectName = {
  "key"    : "value",
  question : "What is the meaning of life?",
  answer   : function(){ return 42 }
}
  • Keys and values are separated by colons
  • key+value pairings are separated by commas
  • The key can have quotations marks or not
    • Avoid spaces in the key name, but if you must have one use quotations marks!
  • The value can be any kind of data! A number, string, array, function, even another object!

Using Objects


const myCat = {
  name  : "Harry",
  age   : 4,
  talk  : function(){console.log("Meow!")},
  state : "hungry"
}
            
  • Accessing a property
  • 
    myCat.name; // Harry
    myCat["name"]; // Harry
    myCat.state; // hungry
              
  • Reassigning a propery
  • 
    myCat.state = "full";
    myCat.state; // full
              
  • Calling a method
  • 
    myCat.talk(); // Meow!
              

"Living" Objects

  • Objects contain information about themselves within themselves
  • This allows developers to give ownership and responsibility to objects...
  • ...making it possible to respresent nearly anything with an object!

Object Example

Let's make a town with buildings, like a bank, and have inhabitants with bank accounts


const bob = {
  name         : "Bob Bobbington",
  age          : 45,
  bank_account : {
      number : "3230-2346-623",
      amount : 502.56
    }
}

const bank = {
  accounts        : [bob.bank_account, sam.bank_account, derek.bank_account],
  location        : "643 Broadway St. NY",
  is_fdic_insured : true
}
  

const town = {
  buildings   : [bank, hospial, gas_station, library],
  population  : 48170,
  inhabitants : [bob, sam, derek],
  state       : "NY"
}
  

Let's Develop It (as a class)

Open up the console in the browser

  • Create a variable using your name and set it to an empty object
    
    const bob = {};
    
  • Add a .age property and set the value to your age
    
    bob.age = 33;
    
  • Add a .phrase method that returns your favorite phrase (make one up if you don't have one!)
    
    bob.phrase = function(){return "Bob's your uncle!"};
        
  • Explore your object! Try calling the .phrase() method, too

JSON

JSON is one of the most common formats used then passing information over the internet

  • JSON stands for JavaScript Object Notation
  • JSON is a raw object or array with the purpose of storing information
  • Contains strings, numbers, booleans, arrays, and objects
  • No methods!

JSON as an object


{
  response: 200,
  results: [
    {
      user : "bobbington",
      password: "pa$$w0rd1!"
    },
    {
      user : "sarah478",
      password: "DROPTABLEusers;"
    },
    {
      user : "rockinKIDD",
      password: "qwerty123"
    }
  ]
}
          

Notice the object stands alone - not assigned to a variable

JSON as an array


[
  {
    name: "Boom Boom Pow",
    artist: "The Black Eyed Peas",
    year: 2009
  },
  {
    name: "Moves like Jagger",
    artist: "Maroon 5",
    year: 2010
  },
  {
    name: "Endless Love",
    artist: "Lionel Richie",
    year: 1981
  }
]
          

Let's Develop It!

In the "mainProject" folder, go into "class_2", and view the "index.html" file in the browser

  • Explore the "questionObj" object defined in the "script.js" file
  • How would you do the following:
    • Access the question?
    • Change the difficulty to "hard"?
    • Create a new property, "image_url", and set it to "games.png"
    • Access the 2nd item in the array?
    • Add "PAC-MAN" to the array?

Let's Develop It! - Answers


// Access the question
questionObj.question
        

// Change the difficulty to hard
questionObj.difficulty = "hard";
        

// Create a new property, "image_url", and set it to "games.png"
questionObj.image_url = "games.png";
        

// Access the 2nd item in the array
questionObj.incorrect_questions[1]; // Ubisoft
        

// Add "PAC-MAN" to the array
questionObj.incorrect_questions.push("PAC-MAN");
        

How the browser works

How do we get this...

From this?

What is the DOM?

The browser translates HTML into JavaScript objects known as the Document Object Model

  • An HTML file is just text, but JS objects are "alive"
  • The browser uses the DOM along with CSS and JavaScript files to render the website properly
  • The nested syntax from HTML carries over into the DOM in the form of nodes

From HTML to the DOM

HTML


<html>
  <head>
    <title>My Site</title>
  </head>
  <body>
    <h2>Some Title</h2>
    <p>First paragraph</p>
    <p>Second paragraph</p>
  </body>
</html>

DOM

  • Remember, the DOM is just JavaScript!
  • We can access the DOM as well as add, modify, and delete elements as we like
  • NOTE: only elements that are part of the DOM will be rendered

Finding an element(s)

HTML


<html>
  <head>
    <title>My Site</title>
  </head>
  <body>
    <h2 id="mainTitle">Some Title</h2>
    <p>First paragraph</p>
    <p>Second paragraph</p>
  </body>
</html>
  

JavaScript


// document.querySelector returns first matching element found
const h2 = document.querySelector("#mainTitle");

// document.querySelectorAll returns an array of all matching elements found
const all_ps = document.querySelectorAll("p");
  

Modifying elements

DOM nodes/elements are objects with their own properties that can be modified!

JavaScript


// document.querySelector returns first matching element found
const h2 = document.querySelector("#mainTitle");
h2.innerText = "Something else!";
h2.style.color = "red"; 
      

BEFORE

AFTER

Creating elements

JavaScript


// document.createElement() creates a new node of the given tag string
const newH3 = document.createElement("h3");
newH3.innerText = "Some text";
  

BEFORE

AFTER

Where is the h3?

Creating elements

The node is not attached to the DOM, therefore it won't be rendered!

Appending elements

Elements must be attached, or appended, to another element in the DOM to be rendered in the browser


// document.createElement() creates a new node of the given tag string
const newH3 = document.createElement("h3");
newH3.innerText = "Some text";

const body = document.querySelector("body"); // document.body
body.append(newH3);

Removing elements

Removing elements from the DOM is as easy as .remove()


newH3.remove();
            
  • .remove() removes the element and all of it's attached children from the DOM
  • If you keep a reference to the object (like in a variable), it still exists, just not as part of the DOM!

Let's Develop It!

In the "mainProject" folder, go into "class_2", and edit the "script.js" file

  • Store the #content-container element in a variable
  • Create a function "addP" that takes a string for a parameter. The function:
    1. Creates a <p> element
    2. Uses the string argument to set the .innerText of the <p>
    3. Appends the <p> to the #content-container

<br />

Let's Develop It!

In the "mainProject" folder, go into "class_2", and edit the "script.js" file

  • Create the "addQuestion" function described in the "script.js" file

Take Home Assignment

Additional Resources