DHTML
JavaScript Programming Fundamentals
Interactivity
This is the point where things really start to get interesting. So far, all the scripts you have been writing haven't contained a whole lot of logic. They were simple scripts that spit out variables or worked with strings. Nothing was really too interactive.
Conditionals are what make JavaScript come alive. They allow it to make decisions based on certain information, or conditions. Let's take a look at conditionals.
Conditionals - If/Then/Else
With conditionals we start to get into real programming. If/then/else conditionals are present in almost every modern programming language, object oriented or not.
What the conditional allows us to do is to say: "If a condition is met, do something. If not, do something else, or nothing at all".
Unlike some other programming languages, JavaScript doesn't actually use the word "then". Instead, it uses curly braces to enclose the then part of the conditional.
Conditionals in JavaScript can take the following form:
if (some condition) {
do something;
}
If the condition contained in the parentheses is true, then the script will look at the content inside the curly braces, and act on whatever is there. If the condition is false, then the script will look for the else part of the conditional and act on whatever is contained in its curly braces.
If the condition is false, and there is no else statement, the script will continue on and ignore everything within the curly braces of the conditional, as if it wasn't there in the first place.
The above example would do something if the condition was met, and nothing at all if it wasn't. There are a few things to keep in mind when writing conditionals.
- The actual condition must always be inside parentheses.
- The part of the if statement that does something if the condition is met should be inside curly braces
Conditionals with else sections can take the following form:
if (some condition) {
do something;
}
else {
do something else;
}
This example is similar to the one above it, only it contains an else section to be carried out if the condition is false.
This is only one way to write a conditional. There is no rule that says the curly braces have to be where they are, and no rule that says that the statements inside the curly braces must be indented. This just makes the code a little easier to understand. The same conditional above could also be written as:
if (some condition){do something;}else{do something else;}
We find this a lot hard to read, however. This will also get much, much harder to read for larger, more complex conditionals.
There is alternate, shorter way to write a conditional that takes the form:
(some condition) ? do something : or do something else
We won't be using this form at all in this course, as it is not as easy to use. But we want to make you aware of it in case you ever see it somewhere are wonder "What the heck??".
Remember comparison operators? This is where you will start to see them in heavy use. One of the most commonly used comparison operators is the == operator. When you see it in a conditional, it will look like this:
if (some_variable == some value) {
do something;
}
You will also be using the && comparison operator, although probably not in the same way. It is commonly used to see if two or more conditions are true. For example:
if ((some_variable == some value) && (another_variable == another value)) {
do something;
}
Pay special attention to the extra parentheses in the above conditional. You can think of this as two conditions inside another condition. Therefore, the extra parentheses are necessary. If you leave them out of a conditional like this one, then you will get an error.
Writing Logical Scripts With Conditionals
Sometimes it can be difficult to write complex scripts that use a lot of conditionals. The easiest way to work things out when programming conditionals is to think through what is supposed to happen. Sometimes even saying it aloud helps, or writing it down.
Here is an example of a real life conditional statement:
Little Johnny has $10 in his pocket. He would like to go and see his favourite rock star in concert, but the concert costs $20, which he doesn't have. There is, however, a movie theater next to the concert showing a movie he really wants to see, and it only costs $10 (including tax) for admission.
As humans, we take these kinds of dilemmas in stride and don't even think twice about them. Little Johnny is most likely going to go see the movie that he wanted to see anyway, because he has enough money to see it, but not enough for the concert. We could write this out (not in code yet) like this.
pocket change = 10
movie = 10
concert = 20
If concert is equal to pocket change, then go to concert.
Or else,
If movie is equal to pocket change, then go to movie.
Now, we have a simplified idea of little Johnny's dilemma. Let's write it out as code. Open up a new HTML document and start scripting.
var pocket_change = 10;
var movie_cost = 10;
var concert_cost = 20;
if (concert_cost <= pocket_change) {
alert('Yay! I\'m going to a concert!');
}
else {
alert('Oh well, I wanted to see this movie anyway!');
}
This code will actually work. Put it into an HTML file and try it out.
In the case of this example, the result will always be the same, because all the variables are fixed. Let's add some user input into the fray. We'll make little Johnny beg for money outside the concert hall. (new code is in bold)
var pocket_change = 10;
var movie_cost = 10;
var concert_cost = 20;
charity = prompt('Please give me some money? Puh leaze?','');
pocket_change = pocket_change + charity;
if (concert_cost <= pocket_change) {
alert('Yay! I\'m going to the concert!');
}
else {
alert('Oh well, I wanted to see this movie anyway!');
}
If you run this script, you may notice that no matter how much money you give Johnny, he still gets to go to the concert. The little rugrat! What's he up to? Well we can find out by putting an alert() just before the conditional like this:
alert(pocket_change);
Now if you run the script, and give Johnny 2 dollars, your pocket_change is 102 dollars. (No, Johnny didn't pick your pocket.) JavaScript simply assumed that the number you entered into the prompt was a string, not a number. This can sometimes happen. What we need to do now is turn the charity variable into a number. We can do that using the parseInt() function. Put the following line of code right after the prompt statement.
charity = parseInt(charity);
JavaScript contains something called global functions. These are built-in functions that are not tied to the DOM. They can be used anywhere, and on many different objects. They are basically used to convert one type of data to another. The parseInt() function is one of them. We will be looking at more global functions throughout this course.
The parseInt() function changes the string into a number, or more specifically, an integer. We then assign this amount back into the charity variable. Run your script again, and once the pocket_change amount looks right again, delete (or comment out) the alert() method.
Now our script should finally be working. If you give the little beggar 5 dollars, he still doesn't have enough money to get into the concert, so he has to go to the movie (at least now he has money for popcorn). If you give him 10 dollars or more, then he has enough to go to the concert.
You can see a working version of this script here.
Congratulations. You've just used a JavaScript conditional to simulate a real-life decision, and you've created a truly interactive JavaScript application, in that the outcome is determined be user input.
Loops
Loops are another very necessary part of any programming language, including JavaScript. A basic loop allows you to run a particular action over and over again, until a condition is met, or while a condition is true.
While Loops
There are several ways to perform a loop in JavaScript. The easiest of these is the while loop.
A while loop takes the following form:
while (some condition is true) {
do some action;
}
To illustrate how a while loop works, we can go back to our Little Johnny saga again. Let's say that after watching his movie (or seeing his concert, whichever he had enough dough for), Johnny has now realized that he can make a lot of money just asking people for money. So now, he's going to sit outside and ask for money until he has enough money to buy himself a cool new scooter. Here's how we could write this out beforehand.
Pocket change = $10
Scooter = $100
Solution = Ask for money until I have enough for the scooter.
This problem can't easily be solved with a simple if/then/else conditional. For this, we will use a while loop.
// Initial amount of pocket money.
var pocket_money = 10;
// Price of scooter.
var scooter_price = 100;
// Initialize a few variables we'll be using later.
var stop_begging = false;
var permission;
var message = ' ';
// Keep asking for enough money until there is enough to buy the scooter.
while (pocket_money < scooter_price) {
// Ask for some money;
recieved_money = prompt("Could I have some money puh-leaze?","");
// Convert recieved_money into a number
recieved_money = parseInt(recieved_money);
// Add any money taken in to pocket_money.
pocket_money += recieved_money;
alert('So far, I have ' + pocket_money + ' dollars');
// If I have enough money, stop begging.
if (pocket_money >= scooter_price) {
stop_begging = true;
}
}
// If stop begging == true
if (stop_begging) {
permission = confirm("Buy Scooter?");
if (permission) {
alert('Cool... I like it!');
message = 'Wheeeeeee!';
}
else {
alert('Awwww, but I have enough money... Why not?');
message = 'Grumble, Grumble';
}
}
To complete this opus, we can put the following script inside the <body> of the document:
document.write(message);
Here's an example of the complete script in action
Let's make a few observations about the above script.
- As long as
pocket_moneyis less thanscooter_price(100) the while loop will execute. Notice that we didn't use the==comparison operator to check to see if Johnny has 100 dollars yet. If we had used==, then if pocket money equaled more than 100, the loop would keep going. We need to check if it is at 100, but also more than 100. (In case of an exceedingly generous donation.) - Instead of writing
pocket_money = pocket_money + recieved_money, we used the short form:
pocket_money += received_money, which says exactly the same thing but with less characters. - We gave the variable
stop_beggingan initial boolean value offalse, then set it totrueif pocket_money was greater than or equal toscooter_price. Later on, outside the while loop, we did something a little different. Notice the line that has the conditional:if(stop_begging). As long asstop_beggingis notfalseor empty, then the expression istrue. If we had setstop_beggingto 1, the condition would be true as well. You can always substitute(something == true)for(something). They mean the same thing. - Note the new method,
confirm(). Confirm can be used to ask a question to which there is only a yes (ok) or no (cancel) answer. If the user presses "Cancel" then the confirm will return false. Otherwise, if they click "Ok", the confirm will return true. - This is our first example of a nested conditional. Notice that there is an if statement:
if (permission)inside another conditional. If you are going to nest them this way (and you can nest as many as you want), you should indent them in this manner so they are easier to read.
For Loops
There is another way to write a loop in JavaScript that, while more complicated, is actually more common. This is called a for loop.
A for loop in JavaScript takes this form:
for (initial expression ; condition ; increment expression) {
do something;
}
Notice that there are three parts to the for loop, separated by a semicolon (;).
- The initial_expression parameter for the loop is where you usually set the variable that will be counting the loop. This expression is only set once, the first time the loop is encountered. It is not changed in the subsequent times that the loop is repeated. Most programmers use the letter
ifor this variable, which stands for index. It is not always necessary to declare the variable with var here. Some programmers do, and some don't. This variable is usually set to 0 (or sometimes 1). - The second parameter, or condition, is where you set up a condition in a similar way as you did with an if/then/else conditional. The loop will run for as many times as the condition is
true. - The third parameter, or the increment expression, increments the variable by one. The variable incremented is usually the one set in the first parameter.
Besides the three parameters, you have the same curly braces that we saw for if statements earlier. They work the same way here.
This may sound a little confusing at this point, so let's take a look at it in action. Here is a <body> script that will write out 10 lines of text on a page.
// Set a variable my_text to some text.
var my_text = "This is line number ";
/* set i to 1 (we don't want a line number 0), set it to loop only when i is less than 11,
and then increment i by one. */
for (i = 1 ; i < 11 ; i++) {
// Write out my_text, then the value of i, then a line break.
document.write(my_text + i + '<br>');
}
Try this one out yourself or see it in action here.
We set the condition as i < 11, so that the script would write out 10 lines. We could have also written i <= 10 and accomplished the same thing.
One more note about for loops: if you are going to have nested for loops, you can't re-use the same variable in both of them. The reason for this is simple. If your first loop used i for a counter variable, while inside that loop, i would keep the value assigned to it by the loop parameters. If you nested a loop inside this loop and also gave it the i variable, you would reset the value of i, and the loop containing the nested loop wouldn't work properly. If you are going to use nested loops, give them each separate variable names.
Break and Continue
There are two useful statements that can come in handy when programming loops. break, and continue.
A break statement in a loop tells the current loop to quit looping, and the script to leave the loop and resume after the loop's closing }. Where this might come in handy is if a certain condition has been met (besides the one in the loop parameters) that would negate the need for more loops to happen. Here's an example:
/* This script will write out 10 lines like the previous example, but will break
when i reaches a number inputted by the user. */
var my_text = "This is line number ";
stop_printing = prompt('Where do you want me to stop?', ' ');
for (i = 1 ; i < 11 ; i++) {
document.write(my_text + i + '<br>')
if (i == stop_printing) {
break;
}
}
Try this code out yourself, or check it out here.
The continue statement will tell the script to ignore everything after it, but only for the current loop. Here's an example:
/* This script will write out 10 lines like the previous example, but will use
continue to ignore a line when i reaches a number inputted by the user. */
var my_text = "This is line number ";
skip_line = prompt('Which line do you want me to ignore?', ' ');
for (i = 1 ; i < 11 ; i++) {
if (i == skip_line) {
continue;
}
document.write(my_text + i + '<br>');
}
Note that in order for the script to skip the line, we had to put the continue statement before the statement where the line gets written.
Check out an example of this script.
Infinite Loops
One thing that is very important to remember is that it is very easy to create what is called an infinite loop. Infinite loops can cause some browsers to stop responding, or crash. You can avoid infinite loops by being very careful when writing loop statements. Although it is possible to create an infinite for loop, it is generally easier to create an infinite while loop. If the condition that you have set for the loop to look for is always true, the loop will never stop. Infinite loops can be very frustrating, so take care to avoid them when programming.
Interactivity Summary
- Conditionals allow for scripts to become truly interactive.
- Instead of the word "then", JavaScript uses curly braces.
- Everything inside the curly braces will be run only if the condition is true.
- The contents of the else statement will run only if the condition is false.
- Comparison operators are commonly used in conditionals.
- If you are comparing more than one condition, you must use an extra set of parentheses.
- It can be helpful to write out what you want to do with a conditional in plain english before attempting to put it in code.
- The
parseInt()global function is used to convert a string to an integer (number). - While loops are used to loop through a script while a condition is true.
- For loops also loop, but use a set of built in parameters to control how they will loop.
- The
confirm()method is used to illicit a yes or no answer from the user, and returns true if the answer is yes, and false if the answer is no. - Break will cause the loop to quit immediately, and the script will resume after the loop's closing curly brace.
- Continue will cause the script to ignore whatever comes after it in the loop, and go to the next iteration of the loop.
- Infinite loops can cause some browsers to crash. Take care when writing loops to avoid them.
- Google Pay-Per-Click (PPC) Marketing Basics September 16, 3:00 PM - 5:00 PM
- Google Pay-Per-Click (PPC) Marketing Advanced September 23, 3:00 PM - 5:00 PM
- Search Engine Part 1 - Optimization (SEO): On-Page Tactics October 20, 3:00 PM - 5:00 PM
- Blogging for Small Business October 22, 10:00 AM - 12:00 PM
- Search Engine Part 2 - Search Engine Marketing (SEM) : Off-Page Tactics October 27, 3:00 PM - 5:00 PM
- Things to Know Before Starting your Small Business Website November 24, 3:00 PM - 5:00 PM
- Email Marketing 101 - How to be Effective Without Being Spam December 01, 3:00 PM - 5:00 PM
- Google Pay-Per-Click (PPC) Marketing Basics September 16, 3:00 PM - 5:00 PM
- Google Pay-Per-Click (PPC) Marketing Advanced September 23, 3:00 PM - 5:00 PM
- Search Engine Part 1 - Optimization (SEO): On-Page Tactics October 20, 3:00 PM - 5:00 PM
- Blogging for Small Business October 22, 10:00 AM - 12:00 PM
- Search Engine Part 2 - Search Engine Marketing (SEM) : Off-Page Tactics October 27, 3:00 PM - 5:00 PM
- Things to Know Before Starting your Small Business Website November 24, 3:00 PM - 5:00 PM
- Email Marketing 101 - How to be Effective Without Being Spam December 01, 3:00 PM - 5:00 PM
DHTML - TOC - Introduction - Books -
JavaScript Programming Fundamentals - Links - Questions - Quiz -
1 - 2 - 3 - 4 - 5 - 6 - [ 7 ] - 8 - 9 -
