JavaScript also provides a for loop, which formalizes this structure a little more.
Here’s our ice cream code written with a for loop instead:
INITIALIZE
DO CONDITIONAL TEST
EXECUTE CODE BLOCK WHILE CONDITIONAL TEST IS TRUE
CONTINUE AFTER LOOP CONDITION FAILS UPDATE
Q: The while and for loops seem the same to me. When do I use which?
A: In general you can do the same things with a for or a while; however, as you can see with the ice cream example, the for loop is a little more compact, and you might argue the while loop is more readable. So, it really is a matter of which fits best given your situation. In general, for loops get used more for iterating over a fixed number of values (say, over the items in a shopping cart), and while loops are used more to loop until a condition is met (say, giving the user a test until he gets it right).
variable and iteration exercise
BE the Browser
Each of the JavaScript snippets on this page is a separate piece of code.
Your job is to play browser, and evaluate each snippet
of code and answer a question about the result.
Write your answer to the question below the code.
var tops = 5;
while (tops > 0) {
for (var spins = 0; spins < 3; spins++) { alert("Top is spinning!");
}
tops = tops - 1;
}
var count = 0;
for (var i = 0; i < 5; i++) { count = count + i;
}
alert("count is " + count);
for (var berries = 5; berries > 0; berries--) { alert("Eating a berry");
}
Snippet 1
Snippet 3 Snippet 2
What count does the alert show?
How many times do you see the alert, “Top is spinning!”?
How many berries did you eat?
for (scoops = 0; scoops < 10; scoop++) { alert("There's more ice cream!");
}
alert("life without ice cream isn't the same");
Snippet 4
How many scoops of ice cream did you eat?
Check your answers at the end of the chapter.
We’ve been using boolean expressions in for and while statements as a conditional test to decide whether to continue looping. You can also use them to make decisions in JavaScript. Here’s an example:
if (scoops < 3) {
alert("Ice cream is running low!");
}
Here’s our boolean expression, testing to see how many scoops are left.
Make decisions with JavaScript
if (cashInWallet > 5) {
order = “I’ll take the works: cheeseburger, fries and a coke”;
} else {
order = “I’ll just have a glass of water”;
}
If there are < 3 scoops left we then execute the code block.
We can string together more than one test too:
if (scoops < 3) {
alert("Ice cream is running low!");
} else if (scoops > 9) {
alert("Eat faster, the ice cream is going to melt!");
}
Add as many tests with “else if” as you need, each with its own associated code block that will be executed when the condition is true.
javascript conditionals
You can provide a catchall for your if statements as well—a final else that is run if all the other conditions fail. Let’s add a few more if/elses and also a catchall:
Making more decisions... and, adding a catchall
if (scoops == 3) {
alert("Ice cream is running low!");
} else if (scoops > 9) {
alert("Eat faster, the ice cream is going to melt!");
} else if (scoops == 2) { alert("Going once!");
} else if (scoops == 1) { alert("Going twice!");
} else if (scoops == 0) { alert("Gone!");
} else {
alert("Still lots of ice cream left, come and get it.");
}
Notice we changed this to only happen when scoops is precisely 3.
Here’s our catchall; if none of the conditions above are true, then this block is guaranteed to execute.
var scoops = 10;
while (scoops >= 0) {
scoops = scoops - 1;
}
alert("life without ice cream isn't the same");
Insert the code above here...
Write the output here.
We’ve added additional conditions to have a countdown to zero scoops.
Take the code above and insert it into the while loop below. Walk through the while loop and write down the alerts in the sequence they occur. Check your answer at the end of the chapter.
var word1 = "a";
var word2 = "nam";
var word3 = "nal p";
var word4 = "lan a c";
var word5 = "a man a p";
var phrase = "";
for (var i = 0; ______; _____) { if (i == 0) {
phrase = ________________;
}
else if (i == 1) {
phrase = ________________ + word4;
}
_________ (i == 2) {
_______________ = phrase + word1 + word3;
}
_________ (________) {
phrase = phrase + ________ + word2 + word1;
} }
alert(phrase);
phrase i < 3 i < 4
i++
i-- word5
word4
word3 word2
word1 word0
else if i == 3
i == 4
i = 3 else if (i == 0)
i = 0 +
else
A palindrome is a sentence that can be read the same way backwards and forwards! Here’s the palindrome you should see if the magnets are all in the right places.
Code Magnets
This code prints out a well-known palindrome in an alert. The problem is that some of the code was on fridge magnets and fell on the floor. It’s your job to put the code back together again to make the palindrome work. Watch out; there were a few magnets already on the floor that don’t belong here, and you’ll have to use some of the magnets more than once!
Check your answer at the end of the chapter before you go on.
how to put javascript in a page
I was told we’d be putting JavaScript in our web pages. When are we going to get there, or are we just going to keep playing around with JavaScript?
Yes, that is the point. First, you needed to know a few basics. Here’s what we’ve done so far: you know how to declare and use JavaScript variables, and you know how to build basic statements and expressions. You also know how to use all those together to write conditional code with if/else statements, not to mention do things
iteratively with while and for statements.
With that under your belt, now we’re going to see how to place JavaScript in your page, and more importantly, how JavaScript interacts with your page. That is, how you determine what’s in your page, how you change your page, and, a bit more down the road, how you write code to react to things happening in your pages.
So, while we’re not done with JavaScript yet, your wait is over; it’s time to see how markup and behavior work together...
HTML file
<head>
<body>
<script>
statement statement
</script>
<script>
statement
</script>
<script src=”mycode.js”>
</script>
How and where to add JavaScript to your pages
Place your script inline, in the <head> element.
The most common way to add code to your pages is to put a <script> element in the head of your page. When you add JavaScript in the <head> element, it is executed as soon as the browser parses the head (which it does first!), before it has parsed the rest of the page.
Add your script by referencing a separate JavaScript file.
You can also link to a separate file containing JavaScript code. Put the URL of the file in the src attribute of the opening <script> tag and make sure you close the script element with
</script>. If you’re linking to a file in the same directory, you can just use the name of the file.
Add your code in the body of the document, either inline or as a link to a separate file.
Or, you can put your code right in the body of your HTML. Again, enclose your JavaScript code in the <script> element (or reference a separate file in the src attribute). JavaScript in the body of your page is executed when the browser parses the body (which it does, typically, top down).
To use JavaScript you’ve got to add it to a web page. But where and how? You already know there is a <script> element, so let’s see where we can use it and how that affects the way JavaScript executes within your pages. Here are three different ways you might add code to your page:
Most of the time code is added to the head of the page. There are some slight performance advantages to adding your code at the end of body, but only if you really need to super-optimize your
page’s performance.
You can type your code right into your web page, or reference a separate JavaScript file
using the src attribute of the script tag.
Or you can place your code (or a reference to your code) in the body.
This code gets executed as the body is loaded.
Place <script> elements in the
<head> of your HTML to have them executed before the page loads.
interaction with a page
JavaScript and HTML are two different things. HTML is
markup and JavaScript is code. So how do you get JavaScript to interact with the markup in your page? You use the
Document Object Model.
How JavaScript interacts with your page
It’s through reading, reacting to, and changing the DOM that JavaScript can be used to write interactive web pages/apps. This book will show you how.
We call this the Document Object Model, which you can ask to tell you anything about the structure or content of your page.
html head
title script
body
h1 h2 p
em
Your browser When you load a page into the
browser, the browser parses the HTML and creates an internal model of your document, that contains all the elements of your HTML markup.
Your JavaScript can interact with the DOM to get access to the elements and the content in them. JavaScript can also use the DOM to create or remove elements (among a number of other things we’ll be getting to).
We call this the DOM, for short.
1
2
When JavaScript modifies the DOM, the browser updates the page
dynamically, so you see new content on your page.
3
Ingredients
One well‑formed HTML5 page One or more web browsers
Instructions
1. Start by creating a document node at the top.
2. Next, take the top level element of your HTML page, in our case the <html> element, call it the current element and add it as a child of the document.
3. For each element nested in the current element, add that element as a child of the current element in the DOM.
4. Return to (3) for each element you just added, and repeat until you are out of elements.
How to bake your very own DOM
Let’s take some markup and create a DOM for it. Here’s a simple recipe for doing that:
<!doctype html>
<html lang="en">
<head>
<title>My blog</title>
<meta charset="utf-8">
<script src="blog.js"></script>
</head>
<body>
<h1>My blog</h1>
<div id="entry1">
<h2>Great day bird watching</h2>
<p>
Today I saw three ducks!
I named them
Huey, Louie, and Dewey.
</p>
<p>
I took a couple of photos...
</p>
</div>
</body>
</html>
document
document html
document
head body
html
We’ve already fully baked this DOM for you.
Turn the page to see the finished DOM.
introducing the document object model
document is always at the t op.
document is a special part of the tree that you can use in JavaScript to get access t o the
entire DOM. These are like the
branches of the tree.
These are like the leaves of the tree (because there are no elements inside them, just text).
document
head
title script
body
h1
meta div id=”entry1”
h2 p p
document is also like the root of an upside down tree.
My blog
Great day bird watching
Today I saw three...
I took a couple of photos...
The DOM includes the content of the page as well as the elements. (We don’t always show all the text content when we draw the DOM, but it’s there).
My blog
html
A first taste of the DOM
The beauty of the Document Object Model is that it gives us a consistent way, across all browsers, to gain access to the structure and content of the HTML from code. That’s huge. And we’re going to see how all that works in a sec...
Back to our example; if you follow the recipe for creating a DOM you’ll end up with a structure like the one below. Every DOM has a document object at the top and then a tree complete with branches and leaf nodes for each of the elements in the HTML markup. Let’s take a closer look.
Now that we have a DOM we can examine or alter it in any way we
want.
We compare this structure to a tree because a “tree” is a data structure that comes from computer science.
<!doctype html>
<html lang="en">
<head>
<title>Movies</title>
</head>
<body>
<h1>Movie Showtimes</h1>
<h2 id="movie1" >Plan 9 from Outer Space</h2>
<p>Playing at 3:00pm, 7:00pm.
<span>
Special showing tonight at <em>midnight</em>!
</span>
</p>
<h2 id="movie2">Forbidden Planet</h2>
<p>Playing at 5:00pm, 9:00pm.</p>
</body>
</html>
Your job is the act like you’re the browser. You need to parse the HTML and build your very own DOM from it. Go ahead and parse the HTML to the right, and draw your DOM below. We’ve already started it for you.
BE the Browser
Draw your DOM here.
document
html
Check your answer with our solution at the end of the chapter before you go on.
relationship between javascript and the dom
Or, how two totally different technologies hooked up.
HTML and JavaScript are from different planets for sure.
The proof? HTML’s DNA is made of declarative markup that allows you to describe a set of nested elements that make up your pages. JavaScript, on the other hand, is made of pure algorithmic genetic material, meant for describing computations.
Are they so far apart they can’t even communicate? Of course not, because they have something in common: the DOM. Through the DOM, JavaScript can communicate with your page, and vice versa. There are a few ways to make this happen, but for now lets concentrate on one—
it’s a little wormhole of sorts that allows JavaScript to get access to any element, and it’s called getElementById.
Let’s see how it works...
Let’s start with a DOM. Here’s a simple DOM; it’s got a few HTML paragraphs, each with an id identifying it as the green, red or blue planet. Each paragraph has some text as well. Of course there’s a <head> element too, but we’ve left the details out to keep things simpler.
Now let’s use JavaScript to make things more interesting. Let’s say we want to change the greenplanet’s text from “All is well” to “Red Alert: hit by phaser fire!’ Down the road you might want to do something like this based on a user’s actions or even based on data from a web service. But we’ll get to all that; for now let’s just get the greenplanet text updated. To do that we need the element with an id of greenplanet. Here’s some code that does that:
document.getElementById("greenplanet");
Here we’re asking the document to get us an element by finding the element that matches the given id.
Remember the document represents the entire page in your browser and contains the
complete DOM, so we can ask it to do things like find an element with a specific id.
p
getElementById(“greenplanet”) returns the paragraph element corresponding to “greenplanet”...
...and then the JavaScript code
can do all sorts of interesting things with it..
body
p id =”greenplanet” p id =”redplanet” p id =”blueplanet”
All is
well Nothing to
report All systems
A-OK head
html document
using getelementbyid
Once getElementById gives you an element, you’re ready do something with it (like change its text to “Red Alert: hit by phaser fire!”). To do that, we typically assign the element to a variable so we can refer to the element thoughout our code; let’s do that and then change the text:
var planet = document.getElementById("greenplanet");
planet.innerHTML = "Red alert: hit by phaser fire!";
Here’s our call to getElementById, which seeks out the “greenplanet”
element and returns it.
We’re assigning the element to a variable named planet.
And in our code we can now just use the variable planet to refer to our element.
We change the content of the greenplanet element to our new text... which results in the DOM (and your page) being updated with the new text.
Red Alert: hit by phaser fire!
body
p id =”greenplanet” p id =”redplanet” p id =”blueplanet”
Nothing to
report All systems
A-OK head
html document
We can use the
innerHTML property of our planet element to change the content of the element.
We’ll talk more about properties of elements shortly...
Any changes to the DOM are reflected in the browser’s rendering of the page, so you’ll see the paragraph change to contain the new content!
Here’s a DOM with a secret message hidden in it. Evaluate the code below to reveal the secret! The answer is upside down on this page.
document.getElementById("e7") document.getElementById("e8") document.getElementById("e16") document.getElementById("e9") document.getElementById("e18") document.getElementById("e13") document.getElementById("e12") document.getElementById("e2")
Write the element each line of code selects, as well as the content of the element to reveal the secret message!
but
strong id=”e13”
TheIt ain’t
document html has come
h1 id=”e1” p
h2 id=”e3” div id=”e4” p id=”e5”p id=”e10” braggin’backit up!I’m not
funnyI do ul li id=”e15” li id=”e16”
li id=”e17” li id=”e18”
li id=”e19” Please turn
the pages
one at a time!
a lot em id=”e12”strong id=”e14” laugh span id=”e6” if
span id=”e7” you
span id=”e8” can
p
time
time id=”e2”
div id=”e11” p id=”e9”
Secret Message
titlemetascript
bodyhead
Answer: “Y ou can turn back pages but not time”
testing the dom code
<!doctype html>
<html lang="en">
<head>
<title>Planets</title>
<meta charset="utf-8">
<script>
var planet = document.getElementById("greenplanet");
planet.innerHTML = "Red alert: hit by phaser fire!";
</script>
</head>
<body>
<h1>Green Planet</h1>
<p id="greenplanet">all is well</p>
<h1>Red Planet</h1>
<p id="redplanet">Nothing to report</p>
<h1>Blue Planet</h1>
<p id="blueplanet">all systems a-Ok</p>
</body>
</html>
Test drive the planets
You’ve seen how to use document.getElementById to get access to an element, and how to use innerHTML to change the content of that element. Let’s do it for real, now.
Here’s the HTML for the planets; we’ve got a <script> element in the head where we’ll put the code, and three paragraphs for the green, red, and blue planets. If you haven’t already, go ahead and type in the HTML and the JavaScript to update the DOM:
We’ve added the JavaScript to the head
of the page.
Here’s the <p> element you’re going to change with JavaScript.
After you’ve got it typed in, go ahead and load the page into your browser and see the DOM magic happen on the green planet.
UH OH! Houston, we’ve got a problem, the green planet still shows “All is well”. What’s wrong?
Just like you saw before, we’re getting the <p> element with the id “greenplanet” and changing its content.