From last week's homework
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 work together to create some code that describes the properties of some safari animals.
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'];
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;
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.');
}
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);
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.
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 work together to add some methods to our code that describes the safari animals.
JS provides several built-in objects:
Let's look at how we can use JavaScript to make websites interactive!
A website is a way to present your content to the world, using HTML and CSS to present that content & make it look good.
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."
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>
<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>
Your browser automatically builds a Document object to store the DOM of a page. To change a page:
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');
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');
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);
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];
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 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');
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';
Isolate a node (an element on the page) and change an attribute or add a new style.
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.