MrFortna.com

JavaScript Tutorial & Assignments

<Back

Introduction

JavaScript is a simple programming language that works within an HTML document. It uses the web browser of the person viewing your webpage to make calculations and perform certain tasks such as changing the content of the page based on what the user is doing. This is known as "client-side scripting."

Like everything else in HTML, JavaScript starts with a tag. It looks like this:

<script>

This tag may appear in the <head> or <body> section, but for the time being, let's stick with putting everything in the <body>.

Also, like everything else, you must tell the web browser where the script ends, like this:

</script>

You may have multiple instance of JavaScripts on one page but they must all be contained within <script> tags.

This script won't do anything spectacular. In fact, it won't do anything at all because we haven't told it to yet. So let's start programming.

Create a new "Javscript" folder and start a new HTML file named "index.htm". Type "JavaScript Library" at the top of the page. Then start adding and working with the following scripts:


  1. Document Write
  2. One Variable
  3. Two Variables
  4. Alert Boxes
  5. Functions
  6. Functions with Variables
  7. Dates
  8. If / Else
  9. Confirm Boxes
  10. innerHTML
  11. Rollovers
  12. Arrays 1
  13. Arrays 2 - Length
  14. Arrays 3 - Replace & Uppercase
  15. Prompt Boxes
  16. Random Numbers
  17. Random Numbers + Arrays
  18. Text Input
  19. Change Text Colors
  20. For Loops
  21. For Loops + Arrays
  22. Working with Dates 1
  23. Working with Dates 2

Document Write

<script>
document.write("Hello World!")
</script>

"document.write" is the JavaScript command to print something to the screen. Here you are telling it to write the traditional first attempt at using a new coding language, "Hello World!". Copy and paste this code into your document. Save your file and view it in a browser. Did it work?

Now, can you change the message?

Next, know that you can combine JavaScript text with HTML tags, like this:

<script> 
document.write("<P>How are <I>you</I>?</P>")
</script>

First assignment: Alter the "Hello World!" text to say something else, combine it with HTML tags to format it.


One Variable

<script>
var message = "How are you?"
document.write(message)
</script>

Variables can be very powerful tools in JavaScript. Think of them as containers to hold important information. In this case we've declared that we're using a variable by typing "var". Then we've given that variable the name "message". Then we've placed the text "How are you?" inside of that variable named "message."

That variable by itself isn't going to do anything, but we can retrieve the contents of that variable at any time. In this case we're asking the browser to print the contents of our variable, "message", on screen.

Copy and paste this code into your document. Does it work?

Now, can you change the contents of the "message" variable to say something else?

Can you change the name of the variable? Does it still work?

Very important: Now would be a good time to point out that JavaScript is case-sensitive. A variable named "message" and a variable named "Message" (with a capital letter) would be two different variables. Pick the way you're going to type your words now (UPPERCASE, TitleCase, lowercase) and stick with it.

Very important: You can't give a variable any name. First of all, every variable name must be one word. "Message 1" isn't going to work. Secondly there are many words like name and date that are "reserved" by JavaScript to do other things. You may not use reserved words for variables. Here's a list of reserved words.

Assignment #2: Give the variable a different name and make it say something other than "How are you?"


Two Variables

<script>
var message1 = "I'm fine."
var message2 = "How are you doing?"
document.write(message1 + " " + message2)
</script>

You're not limited to using one variable in a program. You can use many. Here we've defined and named two variables and filled them with text. Then we've recombined them in one document.write line.

Copy and paste this code into your document. Does it work?

Very important: You can use either double quotation marks or single quotation marks to signify the beginning and end of your message, but you cannot include the same quotation marks in the message itself or the browser gets confused. Both of the following will cause problems. Can you see why?

var message1 = 'I'm fine.'
var message2 = "He said "Fine" and stormed out."

Assignment #3: Give both variables different names and change the messages. Then add a third variable. Combine all three into one line using document.write.


Alert Boxes

Did you click that button? Pretty cool, huh? Here's how it works:

<input type="button" value="Click here!" onClick="alert('Wow!')">

This time around we don't actually need <script> tags. Sometimes HTML and JavaScript work together so well, we can write them both in one line. That's what's going on here. <input type="button"> is the HTML code for a button and "value" specifies what the button says. The rest of the line is JavaScript. "onClick" is an event; it refers to when the user clicks on something, in this case, the button itself. The word "alert" is another JavaScript code. It's what causes the alert box to pop up. The text inside the parentheses is what the alert box will say.

Very important: Pay very close attention to the quotes used in this example. All of the quotations are started and ended with the same type of quote (single or double). When you need to use a set of quotes inside of another set of quotes, you need to switch from using double quotes to single quotes. Getting your quotes mixed up or improperly "nested" will ruin your program.

Assignment #4: Make your own button with your own text that launches an alert box with your own message.


Functions

It doesn't look much different from the previous script, but functions can be a very valuable tool for your programs. Imagine if you needed to run basically the same lines of code in several different places on the page. You could just re-write your code for each instance, but wouldn't it be nice if you could sort of "record" that piece of the program once and "play" it whenever you needed? Functions do just that. They are sort of like programs within programs that you can use over and over again.

Here's how they work. This time there are two parts to the code. First we "record" the function:

<script>
function popUpMessage() {
   alert("Hey, Man!")
   }
</script>

The first step is to declare your function. Then the function is given a name, in this case "popUpMessage()". Functions always end in () kind of like they did in spreadsheet functions, remember? After the function is declared and named we use curly-cue brackets (also called "braces") to define where the function starts and ends. These funny brackets are on top of the square brackets on your keyboard.

Inside the function we have a line of code that will pop up an alert box saying "Hey, Man!".

If this were the end of the function, nothing would happen, because we haven't actually "played" the function. That will come elsewhere on the page:

<input type="button" value="Click here!" onClick="popUpMessage()">

Notice that we've made another button and told it that when someone clicks on it, it should run the "popUpMessage" function that we defined earlier.

Important: Just like variables, you need to be very careful about naming your functions. Misspell it by one letter and it won't work. Also, keep an eye on you curly-cue brackets. Your program won't run if you forget the ending bracket.

Assignment #5: Change the name and the message of your function.


Functions with Variables

We can pass variables to our functions so that one function can be made to do different things. Here's how it works:

<script>
function popMsg2(message) {
   alert(message)
   }
</script>

Here we've defined a new function, popMsg2. But instead of leaving the parentheses empty, we've placed a variable in them. That variable will act as a sort of container to catch anything that gets thrown in it. Later, we've asked to see an alert box pop up with whatever message happens to be in that container. Notice that at this point, there aren't any actual messages.

Later on the page, we add three buttons:

<input type="button" value="Click here!" onClick="popMsg2('Hello There!')">
<input type="button" value="Click here!" onClick="popMsg2('How are you?')">
<input type="button" value="Click here!" onClick="popMsg2('I am fine!')">

Each button "calls" or runs the same function, popMsg2, but each button passes along a different bit of text to that function. You will see different results depending on which button you click.

Note: Pay attention to your quotation marks.

Assignment #6: Change the name of your function, and all three messages. Then add one more button with a different message.


Dates

I didn't write that information. The computer did. The moment this page loaded. In fact, if it took you a while to read this far, the time probably isn't correct any more. But anyway, the point is, you can access the time and date of on the computers of the people who visit your webpage. Here's how:

<script>
var d = new Date()
document.write("The current date and time: " + d)
</script>

The key is "new Date()". This is the code that checks the computer to find out the time and date. We asked the browser to store that information in a variable called "d" then we ask the computer to write that information out for us.

Important: Since this is a client-side script, the program is asking the computer of the person visiting your site for the time and date. It's quite possible that your visitor doesn't have the time set correctly on his/her computer. If that happens, your program won't give them the correct time. There's nothing you can do about that.

Also, the time and date are written the instant the page loads into the browser. But after that, there's nothing to tell the browser to keep updating the time. So if you run this code at 9:03am and leave the page open, it will still say 9:03am, even hours later.

Assignment #7: Copy and paste this code into your document. Did it work?

(We'll do more with time and date later.)


If / Else

One of the more powerful tools in any programming language is the ability to analyze a situation and then take different courses of action based on that situation. In JavaScript the way to do that is by using "if" and "else" (and "else if").

First set up a button to call a function:

<input type="button" value="Will I pass this class?" onClick="answerQ()">

Now let's look at that function:

<script>
function answerQ() {
if (0==1) {
   alert("Yes! Of course!")
   }
else {
   alert("No way!")
   }
}
</script>

The function starts like any other, but on the second line we start asking "if." Following that, we write the condition we want to analyze in parentheses. In this case, we're asking the computer to determine if zero is equal to one. And the obvious answer is "no." (Notice that it takes two equals signs to compare two things). Then in curly-cue brackets we tell the program what to do if the condition is true (which it isn't).

Speaking of the two equals signs, here's a list of different comparisons you can make in JavaScript.

If we left it at that, nothing would happen, but we also include an "else" statement to take care of when the condition is not true (which is the case). Again in curly-cue brackets we write a simple alert statement.

Important: Notice how the if and else portions of the code are indented? That is to make it easier to see which bracket goes with which. Without indenting it's very difficult to keep track of what's going on. Keep a close eye on your code; it's very easy to miss a bracket and ruin your program.

Assignment #8: Alter the condition in the if statement so that you get a more favorable answer to your question.


Confirm Boxes

While using alert boxes is fun, sometimes it's nice to have something a little more interactive, like a confirm box. Here's how it works. First we need a button:

 <input type="button" onClick="showConfirm()" value="Show confirm box">

Hopefully by now you can see that this button is calling the function, "showConfirm()".

That function, elsewhere on the document, looks like this:

<script>
function showConfirm() {
var r = confirm("Press a button")
if (r==true) {
   alert("You pressed OK!")
   }
else {
   alert("You pressed Cancel!")
   }
}
</script>

This will take some explaining, but try to follow along. First we define the function. Next we declare a variable, "r" (short for "response"). The data we put into that variable is whatever results from another JavaScript, "confirm" which launches the box with the "OK" and "cancel" buttons. We also supply the text of what we want the confirm box to say.

At that point, we're going to use an if/else statement to determine which course of action to take. If r (the response to the confirm box) is equal to "true" (which means the user clicked "OK") then we're going to let the user know that we know they clicked "OK". If r is not equal to "true," then we're going to let the user know that too.

Assignment #9: Modify all the messages to say something different.


innerHTML

Now things are going to get interesting!

You're not limited to special pop up boxes to make your page more interactive. You can also make changes to just about any HTML element if you know the right code. Here's how this works:

<p id="pText">Now things are going to get interesting!</p>

Starts off pretty easy. The only code on this line you haven't seen before is the id. Id's are very useful because, as the name implies, they identify the element we want to use. There may be many <P> tags on your page, but only one has the id of "pText". That helps the browser locate it.

Very important: Every id on your page must be unique. Two objects can't share the same id or your program may not run properly. Also, like everything else, id's are case sensitive.

Now here's the JavaScript code you'll need, built into the HTML line:

<input type="button" onClick="document.getElementById('pText').innerHTML='Right?'" value="Change text">

The there are several really important parts to this line. "document.getElementById" tells the browser to search all the elements in the whole document looking specifically at the id's. The 'pText' in parentheses is the specific id it is searching for. "innerHTML" tells the browser that whatever was between the two HTML tags (the <P> tags) that belong to this element needs to be changed. And the text after the equals sign is what it should be changed to.

You're basically telling the browser, "Find whatever element has a certain id and then change whatever is in-between the tags to..."

Assignment #10: Modify all the text to say something different and change the id to something else.


Rollovers

Move your mouse over the image below.

Pretty neat, huh? First of all, it's important that you realize that this trick is accomplished by starting off with two similar images of the same size. Here they are:

Then it's matter of changing one for the other when the mouse moves onto and off of the images. The first line of code you need is this:

<img src="ball-pink.gif" id="ball" onMouseOver="switchBlue()" onMouseOut="switchPink()">

It specifies the location and filename of the initial image. Then it gives the img element a unique id, "ball". Then there are two JavaScripts. One telling the browser what function to run when the mouse is over the image, switchBlue(). And one telling it which function to run when the mouse leaves the image, switchPink().

Very important: You need both functions to accomplish this effect. If you just use the first function, the image will switch and then stay that way.

Here are the functions:

<script>
function switchBlue() {
   document.getElementById("ball").src = "ball-blue.gif"
   }
function switchPink(){
   document.getElementById("ball").src = "ball-pink.gif"
   }
</script>			

Just like with innerHTML above, we're finding a specific element by its id and then changing something about it, in this case the image source (.src). We switch it from "ball-blue.gif" to "ball-pink.gif" and back.

Very important: Just like in regular HTML, you need to be accurate with your filenames and paths. If you spell something wrong, or don't place the image in the right place, your function won't work.

Assignment #11: Make your own rollover effect by modifying the code above. Remember that you'll also need two images that should be saved in the same folder as your webpage.


Arrays

First Name:

An array is like a variable except more powerful. It can hold more than one piece of information. Arrays can save you the time of declaring multiple variables when you have a lot of information to store, especially if that information is similar. In this example, we're storing a list of first names. You could write out a different variable for each name, but it will be quicker to use an array. Like this:

<script>
var firstnames = ["Bill","Bob","Joe","Fred","Ralph","John","Paul"]
document.write(firstnames[5])
</script>

The code starts out like any other variable, but then we use square brackets and fill those brackets with names separated with commas.

To access information in the array we call on the variable and then, in square brackets, tell the array the position of the data we want.

So why does the code output "John"? Isn't "Ralph" in the 5 position?

Very important: In JavaScript, the first position is always considered 0. The second position is considered 1, and so on, and so on.

Assignment #12: Modify this script so that the result is "First Name: Fred"


Arrays 2 - Length

Number of people:

Another nice advantage of using arrays is that it's pretty simple to figure out how many items are in an array:

<script>
document.write(firstnames.length)
</script>

Adding ".length" to an array will output the number of items in that array. (This code is referring to the "firstnames" array you created one lesson ago.)

Assignment #13: Add two names to your "firstnames" array then use javascript to confirm that you have nine people.


Arrays 3 - Replace & Uppercase

First Name:

Let's pretend that Bob hates being called "Bob" and prefers to be called "Robert." How can we ensure that his name is displayed the way he wants it? By using ".replace()" which works like this:

<script>
document.write(firstnames[1].replace("Bob","Robert"))
</script>

Here we ask for the second name in our list, which is Bob (remember that javascript starts counting at 0 so the second position is technically position number 1). Then we tell javascript to replace any instance of "Bob" it finds with "Robert". (If there is no "Bob" nothing happens.)

Important: Javascript is case-sensitive: "bob" is not the same as "Bob".

First Name:

Let's also say we want names to display in uppercase. How can we do that without having to re-type everything? By using ".toUpperCase()":

<script>
document.write(firstnames[3].toUpperCase())
</script>

Assignment #14: Using the same "firstnames" array you've been using and everything you've learned in this lesson, display Joe's name, but change "Joe" to "Joseph" and have it display in uppercase letters. You should be able to do this in one line of code.

Important: Javascript will execute the line of code from left to right. Think about the order of your code.


Prompt Boxes

A prompt box is like a Confirm Box in that we can interact with our visitors. Here's how it works:

<script>
function showPrompt() {
var name = prompt("Please enter your name","Harry Potter")
alert("Hello " + name + "! How are you today?")
}
</script>

First we define a function called "showPrompt()." Then we declare a variable called "name," but instead of filling it with text (or a number), we tell the browser to ask the visitor to enter their name by using a prompt. The prompt consists of two parts: the first part is the question you want to ask; and second part (which is optional) is the default value, which is the answer that will show up automatically.

Then we need a button to activate the prompt:

<input type="button" onClick="showPrompt()" value="Show prompt box">

Assignment #15: Change the text on the button, and change the question in the prompt as well as the default answer.


Random Numbers

See that number there? It's a random integer between 0 and 10. Don't believe it? Refresh the page and see if you don't get a different number. As you'll see later, random numbers can help us make our scripts seem more dynamic and interesting. Here's how we generate a random number:

<script>
//return a random integer between 0 and 10
document.write(Math.floor(Math.random()*11))
</script>

This one takes some explanation. First of all, see the line with the two slashes (//)? That line isn't necessary. In fact, it doesn't do anything at all. It's a comment. Comments don't display on the webpage or do anything in the script. Comments are useful if you want to leave yourself a note in the code to remember something later. In this case, it's just a reminder of what the script will do.

Next, we'll work backwards from Math.random(). Math.random() is an instruction to return a random decimal between 0 and 1 (e.g. .2564). If all we wanted was a random decimal between 0 and 1, we'd be done, but we want an integer between 0 and 10. So what do we do?

We need to do something a little weird. We need to multiply by 11. Why 11? Well, Math.random() will occasionally generate a zero, but it will never generate a 1. The closest it will ever get is .9999. And if we never start with 1, multiplying by 10 will never quite get us to 10. So we use 11 instead.

Next comes Math.floor(). Floor is kind of like rounding except that it's always going to round down to the next lowest integer. Why round down? Well, when we multiplied by 11 we raised the possibility of going over 10 (e.g. .9999 x 11 = 10.9989). By flooring the output, we ensure an integer no greater than 10.

Fun Fact: Computers can't really generate "random" numbers. Instead they have a complicated program that generates numbers based on the the current time (measured in milliseconds).

Important: Random truly does mean random. The computer does not remember (or care about) the last number it gave you. The sequence 2, 2, 2, 2 is just as random as 2, 9, 1, 6.

Assignment #16: This is a tricky one. Change the code to generate a random number between 20 and 25.

Hint: You only need to generate a random number between 0 and 5, then add 20 to the result.


Random Numbers + Arrays

See that color there? Try reloading your browser and see what happens. Much like with the random number generator above, we're getting random results. But this time they're text, not numbers. How do we do that? Use an array:

<script>
var colors = ["Red","Orange","Yellow","Green","Blue","Purple"]
var randomNum = Math.floor(Math.random()*6)
document.write(colors[randomNum])
</script>

First of all, look at the "colors" array. It's an array holding text names of the six colors of the rainbow. Now look at variable "randomNum." It's generating a random number between zero and five. Why five? Remember that arrays in JavaScript start with zero, so 0 = "Red", 1 = "Orange", etc. Put them together with "colors[randomNum]" and you've got yourself a script that randomly writes one of the six possible colors of the rainbow.

Assignment #17: Make a new array of at least five items. Then change the randomNum variable so that each of the items in your array has an equal chance of being selected.

Note: If your code outputs the word "undefined" it means you're trying to display an item in your array that doesn't exist. For example, randomNum = 6, but your array only has 5 items.


Text Input

Type your name here:

Want your webpage to interact with your viewer but don't want to use a prompt box? Use a text field instead. Here's how it works. First get your text field set up in HTML. Make sure you specify a unique id for the text field ("Name" in this case):

<p>Type your name here: <input type="text" id="Name"></p>

And then combine some JavaScript with an HTML button:

<input type="button" value="Submit" onClick="alert('Hey ' + document.getElementById('Name').value + '!')">

Assignment #18: Change the text field to ask for something other than a name. Change the text on the button to say something other than "Submit." And change the message in the alert box.


Change Text Colors

Remember when we changed that text earlier? We can do more than change text itself. With the right code we can change many of the attributes of text as well as other components of a webpage. Check it out:

Here's how it works. First you'll need to id what it is you want to change. For example:

<h2 id="heading">Change Text Colors</h2>

And then use these buttons:

<input type="button" value="Red" onClick="document.getElementById('heading').style.color = '#ff0000'">
<input type="button" value="Blue" onClick="document.getElementById('heading').style.color = '#0000ff'">
<input type="button" value="Green" onClick="document.getElementById('heading').style.color = '#00ff00'">

Assignment #19: Make three buttons that change the color of some text on your page different colors. Use colors other than red, blue, and green. Then show Mr. Fortna.

Bonus Lesson: Here's how you can change the color of the background of your page:

<input type="button" value="Red" onClick="document.bgColor = '#ff0000'">

Try it out.


For Loops

See those numbers there? Would you believe that they were generated with only a few lines of code? By using loops you can get a computer to perform the same action a specific number of times or until some condition is met. Here's what the code looks like:

<script>
for (var i=-2; i<=50; i=i+1) {
document.write(i + ", ")
}
</script>

The important part here is the word "for." It's like saying "for as long as." After "for" comes three pieces of information in parentheses: where to start, how long to keep going, and what to do in-between. Each of these involves the variable "i." You can use any variable name but most coders like "i" because it's short and it can stand for "increment" or "iteration."

Here's what the "for" line is saying: Start with i being equal to -2. For as long as i is less than or equal to 50, keep running this code. And every time through the code set i equal to one more than it was last time. After the "for" line come curly cue brackets and in-between those brackets is the code you want to execute each time through the loop — in this case, write whatever "i" is and then add a comma. So when the code executes, it starts at -2, writes the number, adds 1, and keeps doing that until "i" is equal to 50.

Important Note: Think about this. What would happen if your code was: for (var i=100; i>=50; i=i+1) ? Well, it would start at 100, then add 1 and go to 101, then add 1 and go to 102, then add 1 and go to 103, etc., etc. When would it stop? It wouldn't, because continually adding 1 will never get "i" to be less than 50. This is called an "infinite loop" and is to be avoided. In the old days this would lock up a computer's processor until somebody unplugged it. Nowadays there are some built in safeguards to prevent this (your browser will eventually give up and give you an error message).

Fun Fact: Apple Computers Corporate Office is located at 1 Infinite Loop, Cupertino, CA.

Assignment #20: Create a loop that prints out all the integers from 765 to 698 in that order.

Note: You don't have to write i=i+1. You can use this shorthand: i++. Or use i-- to subtract 1 every time.


For Loops + Arrays

Loops come in very handy when writing out the contents of an array:

This is how it works:

<script>
var classes = ["Spanish","Geometry","US History","Art","Study Hall","P.E."]
for (var i=0; i<=classes.length-1; i++) {
document.write(classes[i] + ", ")
}
</script>

First we define an array and fill it with high school classes. Next comes the "for" loop. In the loop we're going to use a little shortcut by typing "classes.length". Rather than count out all the classes we simply ask the computer for the length of the "classes" array (one advantage of this is that we can add to or subtract from our array later without having to change anything else.) In this case there are six classes, so the length is six. Now we use the "for" loop to write out each of those classes. We have to use a little trick when it comes to telling the computer when to stop. While it's true that there are six items in the array, remember that JavaScript starts counting at zero, therefore we need to stop at five, not six. That's why we subtract one from the length.

Assignment #21: Make an array of 10 of your favorite things and use a "for" loop to write them out.


Working with Dates 1

Earlier we displayed the current date and time, but the format was a little obnoxious. There was way too much information. We can pick apart the date and time info and display it however we'd like by doing this:

<script>
var d = new Date()
var month = d.getMonth() + 1
var date = d.getDate()
var year = d.getFullYear()
document.write("Today's Date: " + month + "/" + date + "/" + year)
</script>

You should already be familiar with d=new Date(). Adding .getMonth(), .getDate(), and getFullYear() help us just get the pieces we want, then we can later reassemble them. There's one weird thing to remember about .getMonth(). Remember how JavaScript starts counting at zero? Well it does for months too, so January = 0, February = 1, etc. Therefore we need to add one to get the month number we're expecting.

Assignment #22: Write a script that will display the date European style: date/month/year.


Working with Dates 2

JavaScript doesn't have a built-in way to display the month or day names. But that doesn't prevent us from using our own arrays:

<script>
var d=new Date()
var day=d.getDay()
var month=d.getMonth()
var date=d.getDate()
var year=d.getFullYear()
var dayNames=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
var monthNames=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
document.write("Today is " + dayNames[day] + ", " + monthNames[month] + " " + date + ", " + year)
</script>

Here we've added d.getDay() to get the number of the day of the week. 0=Sunday, 1=Monday, etc. Then we put that data together with an array to display the date information the way we want. Notice that we no longer need to add one from the getMonth().

Assignment #23: Write a script that displays the day, month, and date in Spanish.

Note: Spanish dates look like this: "Hoy es lunes, el 11 de enero de 2021."


Creative Commons License  This work by MrFortna.com is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.