Exercise

JavaScript for Beginners

Class 2

Objects

Objects let us store a collection of properties.


var objectName = { 
  propertyName: propertyValue,
  propertyName: propertyValue,
  ...
};
			  

var aboutMe = {
  hometown: 'Somewhere in Texas',
  hair: 'brown, usually short'
}; 
			  

Objects

Object properties can have values with all of the data types we've seen, including numbers, text, arrays, and other objects.

var aboutMe = {
  hometown: 'Somewhere in Texas',
  hair: 'brown, usually short',
  likes: ['kittens', 'code', 'dancing'],
  birthday: {month: 4, day: 17}
}; 
        

Accessing Objects

You can retrieve values using "dot notation"

var myHometown = aboutMe.hometown;
			  

Or using "bracket notation" (like arrays)


var myHair = aboutMe['hair'];
			  

Changing Objects

You can use dot or bracket notation to change properties


var aboutMe = {
  hometown: 'Somewhere in Texas',
  hair: 'brown, usually short'
}; 
aboutMe.hair = 'blue';
			  

Add new properties


aboutMe.pet = 'cat';
			  

Or delete them


delete aboutMe.pet; // oh noes!!!
			  

Exercise

Create an object to hold information on your favorite recipe. It should have properties for recipeTitle (a string), servings (a number), and ingredients (an array of strings).

Display your recipeTitle, servings, and ingredients list on the page.

var myRecipe = {
  recipeTitle: 'Vegan pancakes',
  servings: 4,
  ingredients: ['ingredients', 'go', 'here']
}
// you need to make an HTML element with id #recipeTitle for this to work
document.getElementById('recipeTitle').innerHTML = myRecipe.recipeTitle;

Objects as function arguments

Just like other data types, objects can be passed into functions:


var WillaTheCat = {
  age: 8,
  furColor: 'orange',
  likes: ['catnip', 'tofurky', 'tuna'],
  birthday: {month: 3, day: 10, year: 2008}
}

function describeCat(cat) {
  console.log('This cat is ' + cat.age + ' years old with ' + cat.furColor + ' fur.');
}

describeCat(WillaTheCat);
			  

Exercise

Write a function that loops through all the ingredients from your recipe object and lists them on your practice.html page.

Your function should have 1 argument, which is an object.

function listIngredients(recipe) {
  var ingredients = recipe.ingredients;
  for (var i = 0; i < ingredients.length; i++) {
    var ingredient = ingredients[i] + ', ';
    document.getElementById('foods').innerHTML += ingredient;
  }
}

listIngredients(myRecipe);
        

Arrays of Objects

Since arrays can hold any data type, they can also hold objects


var myCats = [
  {name: 'Willa', 
   age: 8},
  {name: 'Squeaky',
   age: 12}
];

for (var i = 0; i < myCats.length; i++) {
  var myCat = myCats[i];
  console.log(myCat.name + ' is ' + myCat.age + ' years old.');
}
        

Exercise

  1. Create a new array named recipeBook.
  2. Create a new recipe object.
  3. Add your recipe objects to the recipeBook list using the push() function.
  4. Loop through the recipeBook array to list information about each recipe title and servings on the page.
for (var i = 0; i < recipeBook.length; i++) {
  var recipe = recipeBook[i];
  var servings = recipe.servings;
  var title = recipe.recipeTitle + ', serves ' + servings + ' 
'; document.getElementById('recipeList').innerHTML += title; }

Exercise

JavaScript Puzzle: The Reading List

Object methods

Objects can also hold functions.


var WillaTheCat = {
  age: 8,
  furColor: 'orange',
  meow: function() {
    console.log('meowww');
  },
  eat: function(food) {
    console.log('Yum, I love ' + food);  
  }
};
			  

Call object methods using dot notation:


WillaTheCat.meow();
WillaTheCat.eat('tuna');
WillaTheCat.eat(WillaTheCat.likes[0]);
WillaTheCat.eat(WillaTheCat.likes[1]);
WillaTheCat.eat(WillaTheCat.likes[2]);
			  

Exercise

Add a function to your recipe objects called 'describe.' It should return the recipe title and servings. Hint: reuse your code from your recipeBook loop.

Update your recipeBook loop to call this function in place of the previous describe + display code.

myRecipe.describe = function() {
    return myRecipe.recipeTitle + ', serves ' + myRecipe.servings + ' 
'; } for (var i = 0; i < recipeBook.length; i++) { var recipe = recipeBook[i]; document.getElementById('recipeList').innerHTML += recipe.describe(); }

Built-in methods

JS provides several built-in objects:

Review: Anatomy of a website

Your Content
+ HTML: Structure
+ CSS: Presentation
= Your Website

A website is a way to present your content to the world, using HTML and CSS to present that content & make it look good.

IDs vs. Classes

ID -- Should only apply to one element on a webpage, e.g., A webpage only has one footer.

The "#" is how you tell CSS "this is an id."

Class -- Lots of elements can have the same class, e.g., There can be many warnings on one webpage.

The "." is how you tell CSS "this is a class name."

The DOM Tree

We model the nested structure of an HTML page with the DOM (Document Object Model) Tree. The browser makes a "map" of all the elements on a page.

The DOM: Sample Code


<!DOCTYPE html>
<html>
    <head>
        <title>Test Page</title>
        <style>
            h1 {
             color: red;
            }
        </style>
    </head>
    <body>
        <h1>My Page</h1>
        <p>Hello World!</p>
        <img src="http://placekitten.com/200/300" alt="cat"/>
    </body>
</html>
				

The DOM: Sample Model

Simple DOM Tree

DOM Access

Your browser automatically builds a Document object to store the DOM of a page. To change a page:

  1. Find the DOM node and store it in a variable
  2. Use methods to manipulate the node

Exercise

Save the jumbotron, header and footer elements in your practice.html file as variables.

Use getElementsByClassName, querySelector and getElementsByTagName.

Log each variable to the console to view the HTML associated with each.

var jumbotron = document.getElementsByClassName('jumbotron')[0];
var header = document.querySelector('.header');
var footer = document.getElementsByTagName('footer')[0];

console.log(jumbotron);
console.log(header);
console.log(footer);
        

DOM Nodes: Attributes

You can access and change attributes of DOM nodes using dot notation.

To change this element:


<img id="kittenPic" src="http://placekitten.com/200/300" alt="cat"/>
			  

We could change the src attribute this way:


var imgKitten = document.getElementById('kittenPic');
var oldSrc = imgKitten.src;
imgKitten.src = 'http://placekitten.com/100/500';
			  

DOM Nodes: Changing Attributes

A list of HTML attributes we can change using JavaScript

DOM Nodes: Styles

You can change page css using style

To make this CSS:


body {
  color: red;
}
			  

Use this JavaScript:


var pageNode = document.getElementsByTagName('body')[0];
pageNode.style.color = 'red';
			  

DOM Nodes: More Styles

Change any CSS property with a "-" to camelCase, and be sure to include a unit on any number

To make this CSS:


body {
  background-color: pink;
  padding-top: 10px;
}
			  

Use this JavaScript:


var pageNode = document.getElementsByTagName('body')[0]
pageNode.style.backgroundColor = 'pink';
pageNode.style.paddingTop = '10px';
			  

Exercise

Use JavaScript to change the background color of your practice.html page.

var pageNode = document.getElementsByTagName('body')[0];
pageNode.style.backgroundColor = 'turquoise';
        

Change the font of your h1 element using the same methods and the 'font-family' CSS property.

Change some more CSS properties of your jumbotron, header, and footer elements using your existing variables.

DOM innerHTML

Each DOM node has an innerHTML property with the HTML of all its children. You can use the property to view or change the HTML of a node.

For example, you can overwrite the entire body:


var pageNode = document.getElementsByTagName('body')[0];
pageNode.innerHTML = '<h1>Oh Noes!</h1> <p>I just changed the whole page!</p>'
			  

Or just add some new content to the end


pageNode.innerHTML += '...just adding this bit at the end of the page.';
			  

DOM innerHTML continued

You can also target a particular element

To fill this HTML element:


<p id="warning"></p>
			  

We can select the node and modify it


var warningParagraph = document.getElementById('warning');
warningParagraph.innerHTML = 'Danger Will Robinson!';
			  

Creating New Nodes

The document object also provides ways to create nodes from scratch:


document.createElement(tagName);
document.createTextNode(text);
document.appendChild();
			  

Creating New Nodes: Sample Code


var pageNode = document.getElementsByTagName('body')[0];

var newImg = document.createElement('img');
newImg.src = 'http://placekitten.com/400/300';
newImg.style.border = '1px solid black';
pageNode.appendChild(newImg);

var newParagraph = document.createElement('p');
var paragraphText = document.createTextNode('Squee!');
newParagraph.appendChild(paragraphText);
pageNode.appendChild(newParagraph);
			  

Exercise

Create a new paragraph element and add it to a div on your page.

Events

An 'event' is a type of object that is created when the user interacts with a web page.

For example, JS creates an event when a user clicks an element.


element.onclick = function () {
  //code to execute when the click happens
};
        

Types of Events

There are variety of events. Some of the most common:

  • onclick: The event occurs when the user clicks on an element
  • onmouseover: The event occurs when the pointer is moved onto an element
  • onkeyup: The event occurs when the user releases a key
  • onload: The event occurs when a document has been loaded
  • onfocus: The event occurs when an element gets focus

Events and Code

How do you make an event trigger some code?

  1. Save your event target as a variable
  2. Make a function that does what you want. This is called the event listener.
  3. Attach the function to the event with an event handler (onclick, onload, onscroll)

Listening Functions

Listening functions require the same steps as other things we have practiced- first, you have to save the element you want to target:


var myTarget = document.getElementById('clickMe'); // save as a variable
                

Then add an event handler('onclick') and a function (event listener) to that object:


myTarget.onclick = sayHi;
function sayHi(){
     alert ('Hi!');
}
                

Exercise

Let's use that big green "Click me" button!

Make some JavaScript code fire after a click event. Try adding the event to the HTML and adding a listening function.

Preventing Defaults

Elements like buttons and links have a default behaviors. However, the event objects has a built-in method to handle that:


element.onclick = function (event) {
  event.preventDefault();
};

        

This

The keyword this references the element that the user has just interacted with


element.onmouseover = function (event) {
  console.log(this);
};

element.onclick = function (event) {
  this.style.backgroundColor = 'red';
  this.innerHTML = 'I've been clicked!';
};
        

Exercise

Add this link to your page, then write JavaScript that targets this link:


<a href="http://phillytechsistas.org/" id="link">Philly Tech Sistas</a>
        

When a user clicks the link, the page should display an alert instead of going to the Philly Tech Sistas homepage.

Forms

You can collect information from users to use in functions. The most common method is an HTML form


<form id="temperatureForm">
    <label for="temp">Temperature:</label> <input type="text" id="temp" size="3"/> degrees in 
    <input type="radio" name="tempFormat" value="F" checked />Fahrenheit 
    <input type="radio" name="tempFormat" value="C" />Celsius <br />
    <label for="submitButton"></label> <input id="tempSubmitButton" type="submit" value="Submit" />
</form>
        

Retrieving Form Data

You retrieve the values of form elements using the value property.


var temperature = document.getElementById('temp').value;
console.log (temperature);
        

You can retrieve the value of a form at any time. Try onblur (when a form element loses focus).

Submit buttons

If you are going to retrieve form values with the submit button, be sure to prevent the default action!


var submitButton = document.getElementById('tempSubmitButton');
submitButton.onclick = function () {
    event.preventDefault();
    var temperature = document.getElementById('temp').value;
    console.log (temperature);
}
        

Exercise

Add this form HTML to your page:


<form id="sayMyName">
    <label for="name">Name:</label> <input type="text" id="name" >
    <label for="submit"></label> <input id="submit" type="submit" value="Submit" />
</form>
        

Write event code that collects the name from the page when the form is submitted.

Put the name from the user input onto the page in a new HTML element, or an alert.

Exercise

Let's make a form for users to submit recipes to our recipeBook.

Add this form HTML to your page:

<form id="shareRecipes">
<label for="shareRecipeTitle">Recipe title:</label> <input type="text" id="shareRecipeTitle" ><br>
<label for="shareServings">How many servings?</label> <input type="text" id="shareServings" ><br>
<fieldset>
  <legend>What ingredients do you use?</legend> <br>
  <label for="shareIngredients1"> <input type="text" id="shareIngredients1" ><br>
  <label for="shareIngredients2"> <input type="text" id="shareIngredients2" ><br>
  <label for="shareIngredients3"> <input type="text" id="shareIngredients3" ><br>
  <label for="shareIngredients4"> <input type="text" id="shareIngredients4" ><br>
</fieldset>
<label for="submitSharedRecipe"></label> <input id="submitSharedRecipe" type="submit" value="Submit shared recipe" />
</form>

Exercise

  1. Write event code that collects the recipe title, servings, and ingredients from the page when the form is submitted (use a submit event).
  2. The info should be saved as an object and then added to the recipeBook array.
  3. Use your listIngredients() function to print the recipe to the page after the new recipe object is saved.

Resources

Class Survey

http://bit.ly/2Dtv2gb