Week 6

Homework

Rather than writing out all the pseudo-code for you, I talk through it in the video below. Please take the time to write the pseudo-code out first. If you try and just write code, I'm sure you'll miss steps. Pseudo-code can help you spot simple mistakes. Good luck!

  1. Watch this video
  2. Download this file
  3. Read about event.preventDefault()
  4. Write code

Resources

JavaScript Recipes

Adding/changing an element's value:


// If the element is already on the page:
var el = document.querySelector("img");
el.setAttribute("src", "http://example.com/logo.png");

// If the element is NOT on the page (new el):
var el = document.createElement("img");
el.setAttribute("src", "http://example.com/logo.png");

Adding/changing an element's textContent:


// If the element is already on the page:
var el = document.querySelector("p");
el.textContent = "The quick brown fox...";

// If the element is NOT on the page (new el):
var el = document.createElement("p");
el.textContent = "The quick brown fox...";

Adding an element to the page with text content


// Let's start with something simple:
var el = document.createElement("li");
el.textContent = "Go grocery shopping...";
var parentEl = document.querySelector("ul");
parentEl.appendChild(el);

// Now, we could move the hard-coded values to variables:
var name = "li";
var text = "Go grocery shopping...";
var parent = "ul";

var el = document.createElement(name);
el.textContent = text;
var parentEl = document.querySelector(parent);
parentEl.appendChild(el);

// That's good, but what we really want is a function.
// Now, we can addElements whenever we want.
function addElement(name, parent, text) {
  var el = document.createElement(name);
  el.textContent = text;
  var parentEl = document.querySelector(parent);
  parentEl.appendChild(el);
}

addElement("li", "ul", "Go grocery shopping...");

In that last example, you could imagine now putting that function in a helpers.js file and reference it from any program:


<script> src="helpers.js"></script>