Day 2: Functions and The DOM

Tuesday, May 15, 2018

Lecture Videos

Morning:

Afternoon:

Topics

Functions

  • Function Expressions
  • Function Declarations
  • Function Hoisting (MDN)

Git

DOM

  • Adding HTML content to an existing element with someElement.innerHTML
  • Creating elements with document.createElement
  • Setting style properties with someElement.style.stylePropertyName
  • Appending child elements with someElement.appendChild
  • REM vs EM - The Great Debate

Examples

Functions



  // function declaration - use 'function' keyword
  function aMostExcellentFunction() {
    console.log('This function is great!')
  }

  aMostExcellentFunction() // => 'This function is great!'

  // function expression - defines a function as part of a larger expression syntax
  // (usually assignment to a variable)
  const anotherExcellentFunction = () => {
    console.log('This function is also great!')
  }

  anotherExcellentFunction() // => 'This function is also great!'


DOM

If we start with the following markup:



<div id="my-div"></div>


We can add additional markup to it programmatically using JavaScript. One way is to create new HTMl elements using document.createElement, and adding them by using appendChild. Styling of the element can even be changed by manipulating the element’s style property.



// create an h1 and modify text content and color
const heading = document.createElement('h1')
heading.textContent = "This is the best heading I've ever seen"
heading.style.color = "red"

// get a reference to the existing div and add the heading as a child element
const div = document.querySelector('#my-div')
div.appendChild(heading)


This will produce the following markup:



<div id="my-div">
  <h1 style="color: red;">This is the best heading I've ever seen</h1>
</div>


Presentations

Projects

User Directory

Morning | Afternoon

Homework

  • Create a new function called renderColor that returns a div element.
  • Call that function when adding that div to colorItem.

Bonus Credit

  • Create a new function called renderListItem.
  • Use it to create list items for each stat.

Super Mega Bonus Credit

  • Create a new function called renderList.
  • Use it to create the list for each person’s stats.
  • Call renderListItem from renderList, not directly from handleSubmit.

Super Mega Bonus Credit Hyper Fighting

  • Be Strong! Do not resort to the use of innerHTML. Keep using document.createElement.