JavaScript 101

Class 3

Homework Questions?

From last week's homework

Review

  • Comments
  • Variables
    • Scope
  • Operators
  • Functions
    • Arguments
    • Returning Values
  • If / Else
  • While Loops
  • For Loops
  • Arrays

Ready for new stuff?

Objects

Objects let us store a collection of properties.

var objectName = {
	propertyName: propertyValue,
	propertyName: propertyValue,
	...
};
var aboutMe = {
	hometown: 'Corry, PA',
	hair: 'Blond',
	likes: ['coding', 'knitting', 'chocolate'],
	birthday: {month: 3, day: 27}
};

Let's Develop It!

Let's work together to create some code that describes the properties of some safari animals.

Accessing Objects

You can retrieve values using "dot notation"

var aboutMe = {
	hometown: 'Corry, PA',
	hair: 'Blond'
};
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: 'Corry, PA',
	hair: 'Blond'
};
aboutMe.hair = 'pink';

Add new properties

aboutMe.eyes = 'blue';

Or delete them

delete aboutMe.eyes;

Arrays of Objects

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

var myCats = [
	{name: 'Mabel',
	age: '6'},
	{name: 'Ollie',
	age: '2'}
];

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

Arrays of Objects

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

var mabelTheCat = {
	age: 6,
	furColor: 'grey',
	likes: ['catnip', 'naps', 'snacks'],
	birthday: {month: 11, day: 25, year: 2009}
}

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

describeCat(mabelTheCat);

Let's Develop It!

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).

Try displaying some information about your recipe.

Bonus: Create a loop to list all the ingredients.

Object Methods

Objects can also hold functions.

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

Call object methods using dot notation:

mabelTheCat.meow();
mabelTheCat.eat('brown mushy stuff');

Let's Develop It!

Let's work together to add some methods to our code that describes the safari animals.

Built-in objects

JS provides several built-in objects:

Questions about objects?

JavaScript + HTML

Let's look at how we can use JavaScript to make websites interactive!

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 messages 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 HTML

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<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

DOM Access: By Id

You can find nodes by id using the method:

document.getElementById(id);

To find:

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

We would use:

var imgKitten = document.getElementById('kittenPic');

DOM Access: By Tag Name

You can find certain types of HTML elements using this method:

document.getElementsByTagName(tagName);

To find:

<li>Daisy</li>
<li>Tulip</li>

We would use:

var listItems = document.getElementsByTagName('li');

DOM Access: HTML 5

In newer browsers, you can use other methods too.

Available in IE9+, FF3.6+, Chrome 17+, Safari 5+:

document.getElementsByClassName(className);

Available in IE8+, FF3.6+, Chrome 17+, Safari 5+:

document.querySelector(cssQuery);
document.querySelectorAll(cssQuery);

getElement vs. getElements

Any method that starts with getElement will return a single node.

document.getElementById('uniqueID'); //returns a single node

Any method that starts with getElements will return a array of nodes. To modify a single node, you will need to use bracket notation to select the correct one.

document.getElementsByTagName('p'); //returns multiple nodes
var specficParagraph = document.getElementsByTagName('p')[2];

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: Getting and Setting Attributes

You can also use getAttribute/setAttribute

<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.getAttribute('src');
imgKitten.setAttribute('src', 'http://placekitten.com/100/500');

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';

Let's Develop It

Use this sample code.

Isolate a node (an element on the page) and change an attribute or add a new style.

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);

Let's Develop It!

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

Lunch Time