Exercise
Objects let us store a collection of properties.
var objectName = {
propertyName: propertyValue,
propertyName: propertyValue,
...
};
var aboutMe = {
hometown: 'Somewhere in Texas',
hair: 'brown, usually short'
};
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}
};
You can retrieve values using "dot notation"
var myHometown = aboutMe.hometown;
Or using "bracket notation" (like arrays)
var myHair = aboutMe['hair'];
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!!!
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;
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);
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);
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.');
}
push()
function.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;
}
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]);
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();
}
JS provides several built-in objects:
A website is a way to present your content to the world, using HTML and CSS to present that content & make it look good.
The "#" is how you tell CSS "this is an id."
The "." is how you tell CSS "this is a class name."
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.
<!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>
Your browser automatically builds a Document object to store the DOM of a page. To change a page:
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);
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';
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';
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';
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.
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.';
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!';
The document
object also provides ways to create nodes from scratch:
document.createElement(tagName);
document.createTextNode(text);
document.appendChild();
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);
Create a new paragraph element and add it to a div on your page.
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
};
There are variety of events. Some of the most common:
How do you make an event trigger some code?
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!');
}
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.
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();
};
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!';
};
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.
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>
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).
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);
}
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.
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>