HeadFirst-JavaScript-v5

advertisement
HTML5 Seminar
Ga Tech
March 31, 2012
Barbara Ericson
Barbara Fox
We all start here...
http://www.datamation.com/img/2009/07/art-programming.jpg
CSS for styling colors, position, fonts
"HTML5"
HTML tags and
attributes
whales.htm
<!doctype html>
<html>
<head>
<title>Learn About Whales</title>
<meta charset="utf-8">
<link rel="stylesheet" href="wstyle.css">
<script src="whales.js"></script>
</head>
<body>
<h1>Whales</h1>
<p>Whales are mammals.</p>
<h2>Orca Whale</h2>
<div id="orca"> </div>
</body>
</html>
wstyle.css
body {
background-color: gray
}
h2 {
color:white
}
JavaScript for interactivity and flexibility
whales.js
function init() {
var w = document.getElementById("orca");
w.innerHTML = "Black & white whale";
}
window.onload = init;
...and it looks like this
<title>
CSS changed
background color to gray
and
"Orca Whale" to white
JavaScript added
"Black and white whale"
inside of the <div>
What will I have to
change when moving
from HTML4 to HTML5?
HTML4 vs. HTML5
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Learn About Whales</title>
<link type="text/css" rel="stylesheet" href="wstyle.css">
<script type="text/javascript" src="whales.js"></script>
</head>
<!doctype html>
<html>
<head>
<title>Learn About Whales</title>
...
</head>
HTML4 vs. HTML5
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Learn About Whales</title>
<link type="text/css" rel="stylesheet" href="wstyle.css">
<script type="text/javascript" src="whales.js"></script>
</head>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Learn About Whales</title>
...
</head>
HTML4 vs. HTML5
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Learn About Whales</title>
<link type="text/css" rel="stylesheet" href="wstyle.css">
<script type="text/javascript" src="whales.js"></script>
</head>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Learn About Whales</title>
<link rel="stylesheet" href="wstyle.css">
...
</head>
HTML4 vs. HTML5
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Learn About Whales</title>
<link type="text/css" rel="stylesheet" href="wstyle.css">
<script type="text/javascript" src="whales.js"></script>
</head>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Learn About Whales</title>
<link rel="stylesheet" href="wstyle.css">
<script src="whales.js"></script>
</head>
HTML4 vs HTML5
whales.htm
• simplifies document markup
<!doctype html>
<meta charset="utf-8">
<link rel="stylesheet" href="wstyle.css">
<script src="whales.js"></script>
wstyle.css
• Must use CSS for all
appearance styling
• CSS3
• adds styles like drop
shadows and rounded
borders
• adds selector options
• adds new element tags for
greater semantic content
• deprecates tags and attributes
that were used primarily for
styling appearance vs. semantic
content
whales.js
API's which add JavaScript functionality:
Video, Canvas, Local Storage,Audio,
Forms, Drag & Drop, Geolocation, Sockets,
Web Workers, Offline Caching
Deprecated HTML tags
<applet>
<frame>
<font>
<center>
<u>
For complete list see:
http://www.tutorialspoint.com/html5/html5_deprecated_tags.htm
Deprecated HTML attributes
Attributes removed from most elements:
align
background
bgcolor
border
cellpadding
cellspacing
width
For complete list see:
http://www.tutorialspoint.com/html5/html5_deprecated_tags.htm
HTML4 vs. HTML5
Move all styling to CSS
<body bgcolor="gray">
<h1>Whales</h1>
whales.htm
<p>Whales are mammals.</p>
<h2><font color="white" >Orca Whale</font></h2>
<div id="orca"></div>
</body>
body {
background-color: gray
}
h2 {
color:white
}
whales.css
"HTML5" JavaScript API's


Geolocation
Forms
identify browser location
can require certain fields filled in; verify email,
URL's or phone numbers

Web Workers
manage multiple scripts running concurrently
and in the background to avoid lags


Local Storage
Canvas
store info on desktop computer
draw text, images, lines, circles,
rectangles, patterns, and gradients


Audio & Video more advanced features
Offline Web Apps Applications which will work even when not
connected to the web
Lab 1:
Convert HTML4 to HTML5


Copy Lab1.zip to your computer & unzip it
Using code from PowerPoint slides:



Convert whale.htm to HTML5
Move color styling to CSS
View whale.htm in your browser to verify it
renders properly
Introduction to HTML
Skip HTML, jump to Lab1
HTML Tags





Begin with <
End with >
Tagname in the middle
< tagname >
Identify the structure of the content
(paragraph, image, link, heading, etc.)
If a tag contains content (text, other tags,
etc.) then it will have a closing tag
</tagname>
HTML Attributes



Provide additional information
Located inside an opening tag
Syntax
attributename="value of attribute"
Basic HTML Structure
<!doctype html>
<html lang="en">
<head>
...
</head>
<body>
...
</body>
</html>
The doctype declaration is not usually
referred to as a tag.
Which are tags?
<html>
<head>
<body>
Name the attribute:
lang
What is the value of that attribute?
"en"
Basic HTML Structure
<!doctype html>
<html lang="en">
<head>
...
</head>
<body>
...
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<body>
required first line according to HTML 5
HTML web page in English
top portion contains <title> and
other non-content related items
visible "contents" of the web page
Common HTML Tags in
<head>
<title>
<meta charset="utf-8">
<script src="javascript.js">
<link rel="stylesheet" href="mycss.css">
typically shows in browser tab or when minimized
character-set
external Javascript file
external CSS defining colors, fonts, etc.
<head>
<title>Whale Info</title>
<meta charset="utf-8">
<script src="javascript.js"></script>
<link rel="stylesheet" href="mycss.css">
</head>
Common text tags in <body>
<p>
paragraph
<h1>
<h2>
<h3>
<h4>
<h5>
<h6>
Heading 1 (Major Heading)
SubHeading (subheading of <h1>)
sub-SubHeading (subheading of <h2>)
sub sub ...
sub sub sub ...
smallest sub-heading
<ul>
<ol>
<li>
Unordered list - list items inside will have bullets in front of them
Ordered lists - list items inside will be numbered
individual item in a list (either ordered or unordered)
<h1>Mammals</h1>
<h2>Whales</h2>
<ul>
<li>Orca</li>
<li>Beluga </li>
<li>Humpback</li>
</ul>
HTML Miscellaneous
Comments
<!-- This is a comment. It is ignored by the browser -->
Nesting
Tags should be nested inside of each other like nesting dolls.
To opening tag and closing tag create a "box" that contains other information.
<p>Beginning of a paragraph
<ol>
<li>Orca</li>
</p>
<li>Beluga</li>
</ol>
Try It
Nesting Check
This HTML is not nested properly.
Write down the correct HTML.
Indent to make the nesting more clear.
.
<h3>Favorite Foods</h3>
<ol>Pizza</li>
Cake</li>
<li>Cookies</ol>
<li>Sushi</li>
Nesting Solution
<h3>Favorite Foods</h3>
<ol>
<li>Pizza</li>
<li>Cake</li>
<li>Cookies</li>
<li>Sushi</li>
</ol>
Spacing in HTML
Block tags start on a new line and do a line break when finished:
<p>, <h1>, <h2>, <h3>, <h4>, <h5>, <h6>, <ol>, <ul>, <li>, <div>, <hr>
Inline tags will display beside each other: <a>, <img>, <span>
To force a newline (i.e. line break):
<br>
HTML treats multiple spaces as one space.
Add extra spaces with:
 
<h1>Animal<br>Report<br><br>by
<br>
<br>
Joey</h1>
<h2>Mammal
Report<br>by     Suzanne</h2>
Images


Embed jpg, gif, and png images into web page
Image tags require the use of attributes
<img src="beluga.jpg" alt="Baby Beluga Whale" >
<img src="http://images.nationalgeographic.com/beluga.jpg" alt="Baby Beluga Whale">
Hyperlink aka anchor aka link

A hyperlink is text or an image that you can click on to jump to a new
document (or a different part of the current web page)
internet sites usually begin with http://
<a href="http://www.google.com">Click here to go to Google</a>
local sites do NOT begin with http://
<a href ="whales.htm">Click here to go to the local web page called
whales.htm</a>
<a href ="http://www.w3schools.com/" target="_blank">Great site to
learn about web design</a>
Lab2
Create website
Create a 2-page web site about another teacher
in the room
1.


2.
3.
4.
5.
Create new folder/link called lab2 to hold the files
Create home page: index.htm
Create second page: interests.htm
Add proper HTML5 info in <head>
In <head> add a <title>
In <body> add headings, lists, paragraphs, images, and a link
to an external website
Link index.htm and interests.htm to each other
Note: Workshop site: http://coweb.cc.gatech.edu/ice-gt --> Teacher Workshops
New links created with asterisks: *lab2*
Common HTML Attributes
src="playlist.js"
src="marathon.jpg"
embeds the contents of this file into the web page
href="playlist.css"
href="http://google.com"
hyperlink reference to an external file
id="first"
a unique identification for an
element so it is easy to refer to it
with HTML, CSS, or JavaScript
class="whale"
an identifier than can refer to multiple elements
to make it easy to refer to those elements with
HTML, CSS, or JavaScript
Tables
<table>
<tr>
<th>
<td>
table
row
column or row heading cell (table heading)
regular cell (table data)
1st row - table headings
2nd, 3rd, & 4th row - table data
<table>
<tr>
<th>Whale</th>
<th>Length</th>
<th>Weight</th>
</tr>
<tr>
<td>Blue Whale</td>
<td>100 feet</td>
<td>150 tons</td>
</tr>
<tr>
<td>Sperm Whale</td>
<td>60 feet</td>
<td>50 tons</td> </tr>
<tr>
<td>Killer Whale</td>
<td>30 feet</td>
<td>5 tons</td>
</tr>
</table>
with No CSS Styling
with CSS Styling
Tables - additional tags
<caption>
Table caption
<thead>
Groups the header content
<tbody>
Groups the body content
<tfoot>
Groups the footer content
<colgroup>
Defines a group of columns in a table
(makes it easier to apply CSS)
<col>
Used with colgroups to define styles for columns
Tables - HTML5 attributes
Removed width, cellspacing, cellpadding, and others
Only supported attribute is:
border=""
border=1
No border
border on
Tables - add'l context tags
<table>
<thead>
<tr>
<th>Whale</th>
<th>Length</th>
<th>Weight</th>
</tr>
</thead>
<tbody>
<tr>
<td>Blue Whale</td>
<td>100 feet</td>
<td>150 tons</td>
</tr>
...
</tbody>
</table>
<style>
table {
border: 15px solid navy;
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding:10px;
}
thead {
font-family:sans-serif, arial;
text-transform:uppercase;
border:5px solid gray
}
</style>
Tables - colgroup

Create groups columns for styling
<style>
.whaleinfo{background-color:LightSkyBlue; width: 300px}
.whale {width:100px}
...
</style>
<table>
<colgroup>
<col class="whale"></col>
<col class="whaleinfo"></col>
<col class="whaleinfo"></col>
<colgroup>
...
Lab 2B
Add a table

Add a table to the teacher website
Note: This page will still have boring black text and the
pictures will be sized poorly. That's ok! We can
dress it up later with CSS.
Form Elements - text + button
<form>
<input type="text"
id="songTextInput" size="40" placeholder="Song name">
<input type="button" id="addButton" value="Add Song">
</form>
Later we'll be creating JavaScript that will respond to the button click and
read the text input
Form Elements - radio buttons
<form>
<input type="radio" name="size" value="small" />Small<br>
<input type="radio" name="size" value="medium" />Medium<br>
<input type="radio" name="size" value="large" />Large
</form>
Form Elements - drop downs
<form
action="">
<label>Select your favorite car</label>
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat" selected="selected">Fiat</option>
<option value="audi">Audi</option>
</select>
</form>
Form Elements check box and Submit button
<form>
<input type="checkbox" name="vehicle" value="bike" />bicycle<br>
<input type="checkbox" name="vehicle" value="car" />automobile<br>
<input type="checkbox" name="vehicle" value="bus" />bus<br>
<input type="submit" value="Submit" />
</form>
Submit sends the input from
the form to a web server for
processing
Lab 2C
Add a form
Add a form to your teacher website which includes:
 input type="text" (ask for student name)
 button (Add a Song, Add a Class, etc.)
 radio buttons (age, gender, etc.)
 checkboxes (favorite foods)
 submit button
Note: This page will still have boring black text and the pictures will be
sized poorly. That's ok! We can dress it up later with CSS.
Div
<div>

Divisions are used to separate sections of a web page for



styling (colors, fonts, etc.)
positioning on the page
Contextual sections should be specified using the new HTML5 tags:
<section>
<article>
<header>
<hgroup>
<footer>
<nav>
<aside>
sports, news, ads
Cure For Cancer
Atlanta Journal + logo
group of headers for one topic
page number, contact links
navigation links
pullout
Using <div>
<div id="header">
<div id="links">
<div id="mainContent">
<div
id="article">
<div class="sidebar">
<div id="footer">
diagram from www.cengagesites.com/.../Transitioning to HTML5 and CSS3)Patrick Carey.ppt
Using HTML5 elements
<header>
… </header>
<div id="header">
<nav>
<div
… </nav>
id="links">
<div id="mainContent">
<section>
… </section>
<article>
<div
…</article>
id="article">
<div
class="sidebar">
<aside>
… </aside>
<footer>
<div id="footer">
… </footer>
Note: Not block elements like <div>. Can change to block element behavior with CSS display:block
diagram from www.cengagesites.com/.../Transitioning to HTML5 and CSS3)Patrick Carey.ppt
Div
div id="info"
div id="photos"
Div
<div id="info">
<h1>Animal Report</h1>
<h2>Mammals </h2>
<h3>Water mammals</h3>
<img src="whaleClipart2.jpg">
<h4>Whales</h4>
<h5>Beluga whales</h5>
<h6>Feeding habits of belugas</h6>
</div>
<div id="photos">
<img src="beluga.jpg">
<img src="babyBeluga.jpg">
</div>
Two divisions are created
Div
#photos {
height:250px;
width:650px;
background-color:gray;
border:10px solid black
}
#photos img {
margin:20px;
border:5px solid white;
height:200px
}
only div id="photos"
is affected by the CSS styling
Solution
Introduction to CSS
Skip CSS, jump to Lab 2
CSS


Cascading Style Sheets
Control the appearance or style of the web
page



color, font, border
width, height, position
margin, padding
CSS

Inline CSS



Internal CSS aka Embedded CSS




affects one line of HTML
located within an HTML tag
affects one web page
located in the <head>
<style> .... </style>
External CSS


affects multiple pages of a web site
located in an external file and linked to each page with the
<link> tag in <head>
CSS - w3schools.com
CSS - inline

Inline CSS



affects one line of HTML
located within an HTML tag
no selector since it is inside a tag
<h2 style="color:teal">Teal</h2>
<h2>Not teal</h2>
CSS - internal

Internal CSS aka Embedded CSS



affects one web page
located in <head>
To change ALL <h2>
<style>
h2
{
color:teal;
background-color:yellow
}
</style>
<h2 id="orca">Killer Whale</h2>
<h2> Beluga</h2>
CSS - external

External CSS



affects every web page that include
<link> to the CSS file
Do NOT specify <style>
<link> is in <head> of web page
<!-- This is the file whale.htm -->
<head>
<link rel="stylesheet" href="whale.css">
</head>
<body>
<h2 id="orca">Killer Whale</h2>
<h2> Beluga</h2>
</body>
/* This is the file whale.css */
h2 {
color:teal;
background-color:yellow
}
CSS with ids


The HTML attribute id=" " is used to uniquely identify an
HTML element so JavaScript, CSS, and other HTML can refer
to it
#idname
is the CSS selector for an id
<h2 id="orca">Killer Whale</h2>
<h2> Beluga</h2>
<style>
h2
{
color:red;
}
#orca {
background-color:LightBlue
}
</style>
CSS with classes


The HTML attribute class=" " is used to identify multiple
HTML elements so JavaScript, CSS, and other HTML can
refer to them easily
.classname
is the CSS selector for a class
.whale {
color:red;
}
<h1 class="whale">Killer Whale</h1>
<p class="whale">Another name for a killer whale is an orca</p>
<table>
<tr>
<th>Whale</th>
<th>Length</th>
<th>Weight</th>
</tr>
<tr>
<td>Blue Whale</td>
<td>100 feet</td>
<td>150 tons</td>
</tr>
<tr>
<td>Sperm Whale</td>
<td>60 feet</td>
<td>50 tons</td> </tr>
<tr>
<td>Killer Whale</td>
<td>30 feet</td>
<td>5 tons</td>
</tr>
</table>
with No CSS Styling
with CSS Styling
<table>
<tr>
<th>Whale</th>
<th>Length</th>
<th>Weight</th>
</tr>
<tr>
<td>Blue Whale</td>
<td>100 feet</td>
<td>150 tons</td>
</tr>
<tr>
<td>Sperm Whale</td>
<td>60 feet</td>
<td>50 tons</td> </tr>
<tr>
<td>Killer Whale</td>
<td>30 feet</td>
<td>5 tons</td>
</tr>
</table>
<style>
table {
border: 5px solid red;
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding:10px;
}
</style>
with CSS Styling
CSS3 - border-radius
#whale {
width:400px;
height:250px;
background-color:LightSkyBlue;
padding:15px;
border-radius: 20px;
}
#whale img {
width:50%;
border:15px solid gray;
border-radius: 15px
}
<div id="whale">
<h1>Whales<h1>
<img src="babyBeluga.jpg">
</div>
CSS3 - drop shadows
#blurred {
background-color:LightSkyBlue;
box-shadow: 10px 10px 5px gray;
}
#sharp {
background-color:LightSkyBlue;
box-shadow: 10px 10px black;
}
<h1 id="blurred">Blurred<h1>
<h1 id="sharp">Sharp</h1>
Lab 2D


Create a CSS file called lab2.css in the
labs folder
Add the following line in the <head> section
of index.htm and interests.htm:
<link rel="stylesheet"

href="lab2.css">
Change the styling (See example CSS on
next page or http://w3schools.com to be more
creative)
Sample lab2.css
/* lab2.css */
body { background-color: gray }
h2
{ color: red }
h3
{ text-align:center}
img
{ border: 9px solid blue;
width:200px }
p
{ font-style: italic }
a:hover {color:blue}
/* hover over link color */
What can you do with
JavaScript?
Three places to add JavaScript
<head>
internal script - put in <head> section
<script>
JavaScript statement(s)
external JavaScript file
</script>
<script src="mycode.js">
</script>
</head>
<body>
<script>
JavaScript statement(s)
inline script - put in <body> section
</script>
<body>
Make a statement
Store a value in a variable
Add comments
var temp=98.6;
// fahrenheit
var firstName = "Adam";
var lastName = "Zigler";
temp = (temp - 32) * 5 / 9;
var fullname = firstName + " " + lastName;
Do math
Concatenate strings
var randomNum = Math.random();
var count=5;
count=count+1;
Use functionality built into JavaScript
Add one to an existing variable
Pop up an alert window
alert("Please enter a song");
Try It
Simulate a baseball game.
Create homeScore with value of 10
Create visitorScore with value of 8.
Pop up an alert stating "Game Over"
Challenge: Pop up an alert that prints
the current scores
Hint: "\n" prints a newline
Solution
<head>
<title>Learn JavaScript</title>
<meta charset="utf-8">
<script>
homeScore=10;
vistorScore=5;
alert("Game Over");
// Newline created with \n
alert("Home: " + homeScore + "\nVisitors: " + vistorScore);
</script>
</head>
<body>
</body>
Do things more than once
(while loop)
beanCounter = 5;
while (beanCounter > 0 ) {
alert("Dropped a bean");
beanCounter = beanCounter - 1;
}
Do things more than once (for
loop)
var weight=130;
for (scoops = 0; scoops < 10; scoops++) {
weight=weight+1;
}
This loop will execute 10 times (
1st Iteration: scoops = 0
2nd iteration: scoops = 1
...
9th iteration: scoops = 8
10th iteration: scoops = 9
then scoops=10 so loop exits
weight=131
weight=132
weight=139
weight=140
Try It
Simulate strikeouts with a
for loop.
Alert popups that say:
Strike 1
Strike 2
Strike 3
You're out
Solution
<script>
for (strike = 3; strike >0; strike--)
{
alert("Strike " + strike);
}
alert("You're out!");
</script>
Make decisions and get input
from popup prompt
var name=prompt("Please enter your name","Jane Doe");
if (name!=null && name!="") {
alert("Thank you, " + name)
}
else {
alert("Name entered improperly");
}
!=
""
&&
not equal
empty string
AND (both conditions must be true)
DOM - Document Object Model
<body>
<h1>My awesome playlist</h1>
<ul id="playlist>
<li id="song1"></li>
<li id="song2"></li>
<li id="song3"></li>
</ul>
</body>
html
head
title
body
h1
ul id="playlist"
li id="song1"
li id="song2"
li id="song3"
p. 82
JavaScript code samples
http://www.blogohblog.com/wp-content/pop/2008/07/funnyjavascript.gif
Before changing DOM, page must
be completely loaded
This function changes the value of an existing HTML element
function init()
{
var nm = document.getElementById("name");
nm.innerHTML = "Jessie";
}
window.onload = init;
<body>
<h1 id="name">Your Name Here</h1>
</body>
Create a function
This function changes the value of an existing HTML element
function show_prompt()
Function name
{
var name=prompt("Please enter your name","Jane Doe");
if (name!=null && name!="")
greet refers to element with id="greetings"
{
var greet = document.getElementById("greetings");
greet.innerHTML = "Hello, " + name ;
}
}
innerHTML changes the contents
of the element with id="greetings"
Try It
Prompt the user for their hometown and then
display the result on the webpage.
Potential Solution
<script>
function init()
{
var tn = document.getElementById("town");
tn.innerHTML = prompt("Enter your town","Atlanta");
}
window.onload = init;
</script>
<body>
<h1 id="town">Your Hometown Here</h1>
</body>
Respond to a button click
<head>
<script>
function show_prompt() {
var name=prompt("Please enter your name","Jane Doe");
if (name!=null && name!="")
{
var greet = document.getElementById("greetings");
greet.innerHTML = "Hello, " + name;
Find id="greetings" and
}
change content to "Hello,
}
Jane Doe"
window.onload = show_prompt;
</script>
</head>
<body>
<p id="greetings"></p>
<input type="button" onclick="show_prompt()" value="Click Me">
</body>
Looping
<html>
<head>
<script>
function countdown()
{
var newtext = "Countdown"
var blast =
document.getElementById("blastoff");
for (var i = 10; i > 0; i--)
{
newtext = newtext + "<br>" + i;
}
blast.innerHTML = newtext;
}
window.onload = countdown; // no parentheses
</script>
</head>
<body>
<div id="blastoff">
</div>
</body>
</html>
Arrays
var tempByHour = new Array();
tempByHour[0] = 59.2;
tempByHour[1] = 60.1;
tempByHour[2] = 63;
tempByHour[3] = 65;
tempByHour[4] = 62;
var temps = [59.2, 60.1, 63, 65, 62];
index 0
Arrays
// Add to existing array
tempByHour[5] = 61;
// Get the value of one element of the array
var message = "The temp at 5 pm was
" + tempByHour[5];
// Retrieve the size of the array
var numItems = tempByHour.length;
p. 67
Creating an object with
properties...iterating through the
properties
<html>
<head>
<script>
function count_animals()
{
var animal1={species:"cow",type:"mammal",
weight:300};
var d = document.getElementById("data");
var newdata = "Animal Properties<br>";
for (x in animal1)
{
newdata = newdata + "<br>" + animal1[x];
}
d.innerHTML = newdata;
}
window.onload = count_animals; // no
parentheses
</script>
</head>
<body>
<div id="data">
</div>
</body>
</html>
empty <div> is filled with:
Animal Properties<br>
<br>cow<br>mammal<br>300
Webville Tunes - Chapter 3
Ask user to enter songs and then
add them to a songlist
Webville Tunes - Chapter 3
<!doctype html>
<html lang="en">
<head>
<title>Webville Tunes</title>
<meta charset="utf-8">
<script src="playlist_store.js"></script>
<link rel="stylesheet" href="playlist.css">
</head>
<body>
<form>
<input type="text" id="songTextInput"
size="40" placeholder="Song name">
<input type="button" id="addButton"
value="Add Song">
</form>
<ul id="playlist"></ul>
</body>
</html>
/* playlist.js */
window.onload = init;
function init() {
var button = document.getElementById("addButton");
button.onclick = handleButtonClick;
}
function handleButtonClick(e) {
var textInput = document.getElementById("songTextInput");
var songName = textInput.value;
alert("Adding " + songName);
if (songName == "") {
alert("Please enter a song");
}
else {
alert("Adding " + songName);
var li = document.createElement("li");
li.innerHTML = songName;
var ul = document.getElementById("playlist");
ul.appendChild(li);
}
}
Lab 3


Copy the folder lab3 to your computer
Assignment: Add a line to the bottom of the web page which
displays the total number of songs entered into the play list
Hints:
1.
Edit lab3-playlist.htm and add an <h2> with an
id="numSongs" that will eventually hold the number of
songs. Give it temporary text that says THIS WILL HOLD NUMBER
OF SONGS IN PLAYLIST
2.
Test to make sure your <h2> displays
...continued on next slide...
Lab 3 (cont.)
3.
4.
5.
6.
7.
8.
Edit lab3-playlist.js
Create a global variable called total_songs and set its initial
value to 0
Find the part of the code that gets executed when a song is
successfully entered. Inside that block of code, immediately after
the new <li> gets appended into the <ul>, add code which...
Adds one to the total_songs variable
Creates a variable called sTotal to hold the element identified
by id="numSongs"
Change the innerHTML value of sTotal to
"Total songs:
" + total_songs.toString()
(note: solution can be found in the folder lab3-solution)
Solution - Lab 3
lab3-playlist.html
<form>
<input type="text" id="songTextInput" size="40" placeholder="Song
name">
<input type="button" id="addButton" value="Add Song">
</form>
<ul id="playlist">
</ul>
<!-- Create an h2 here with an id called "numSongs"
that will hold the number of songs in your playlist -->
<h2 id="numSongs">Total Number of Songs in Playlist will be
displayed here</h2>
Solution - Lab 3
lab3-playlist.js
var total_songs = 0;
...
function handleButtonClick() {
var textInput = document.getElementById("songTextInput");
var songName = textInput.value;
if (songName == "") {
alert("Please enter a song");
}
else {
alert("Adding " + songName);
var li = document.createElement("li");
// create new object li
li.innerHTML = songName;
// give it text of user entered songName
var ul = document.getElementById("playlist"); // create new object attached to
id=playlist
ul.appendChild(li);
// append the li object to end of ul
id=playlist
// Solution Additions/////////////////////////////////////
total_songs=total_songs+1;
var sTotal = document.getElementById("numSongs");
sTotal.innerHTML = "Total songs: " + total_songs.toString();
}
Supplemental Lab 4

Copy the folder called lab4 to your computer

Add another input text box and button which creates a list of
Musicians. Make it work just like the Song list.
Hints:

Edit lab4-playlist.htm and copy the form used for
songs. Change the data to reflect musicians.

Edit lab4-playlist.js and add code to allow users to
also enter a list of musicians
(note: solution can be found in the folder lab4-solution)
Solution - Lab 4
lab4-playlist-solution.html
<form>
<input type="text" id="musicianTextInput"
size="40" placeholder="Musician name">
<input type="button" id="addMusicianButton"
value="Add Musician">
</form>
<ul id="musicianlist">
</ul>
Solution - Lab 4
lab4-playlist-solution.js
function init() {
...
var mbutton = document.getElementById("addMusicianButton");
mbutton.onclick = handleMusicianClick;
}
function handleMusicianClick() {
var textInput = document.getElementById("musicianTextInput");
var musician = textInput.value;
if (musician == "") {
alert("Please enter a musician name");
}
else {
alert("Adding " + musician);
var li = document.createElement("li");
li.innerHTML = musician;
var ul = document.getElementById("musicianlist");
ul.appendChild(li);
}
}
Download