Also, like everything else, you must tell the web browser where the script ends, like this:
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.
Now, can you change the message?
First assignment: Alter the "Hello World!" text to say something else, combine it with HTML tags to format it. Show Mr. Fortna when you are done. Be prepared to show both the webpage and the source code.
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?
Assignment #2: Give the variable a different name and make it say something other than "How are you?" Show Mr. Fortna when you are done. Be prepared to show both the webpage and the source code.
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?
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. Show Mr. Fortna when you are done. Be prepared to show both the webpage and the source code.
Did you click that button? Pretty cool, huh? Here's how it works:
<INPUT type="BUTTON" value="Click here!" onClick="alert('Wow!')">
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. Also any time you want text, use quotes. Any time you want a variable, don't.
Assignment #4: Make your own button with your own text that launches an alert box with your own message. Show Mr. Fortna when you are done. Be prepared to show both the webpage and the source code.
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:
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.
Very 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. Show Mr. Fortna when you are done. Be prepared to show both the webpage and the source code.
We can pass variables to our functions so that one function can be made to do different things. Here's how it works:
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.
Assignment #6: Change the name of your function, and all three messages. Then add one more button with a different message. Show Mr. Fortna when you are done. Be prepared to show both the webpage and the source code.
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:
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.
Very 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? Show Mr. Fortna when you are done.
(We'll do more with time and date later.)
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:
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).
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.
Very 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. Show Mr. Fortna when you are done. Be prepared to show both the webpage and the source code.
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:
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. Show Mr. Fortna when you are done. Be prepared to show both the webpage and the source code.
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.
<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. Show Mr. Fortna when you are done. Be prepared to show both the webpage and the source code.
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()">
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:
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. Be prepared to show both the webpage and the source code.
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:
The code starts out like any other variable, but then we write "new Array" and then fill that array 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?
Assignment #12: Modify this script so that the result is "First Name: Fred"
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:
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.)
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:
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()":
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.
A prompt box is like a Confirm Box in that we can interact with our visitors. Here's how it works:
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. Show Mr. Fortna.
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:
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 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 large library of predetermined numbers that are selected based on the time.
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 15 and 30. Show Mr. Fortna when you're done.
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:
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. Show Mr. Fortna when you're done.
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.
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>
<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. Then show Mr. Fortna.
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'">
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.
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:
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 (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. Show Mr. Fortna when you're done.
Note: You don't have to write i=i+1. You can use this shorthand: i++. Or use i-- to subtract 1 every time.
Loops come in very handy when writing out the contents of an array:
This is how it works:
Assignment #21: Make an array of 10 of your favorite things and use a "for" loop to write them out. Show Mr. Fortna when you're done.
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:
Assignment #22: Write a script that will display the date European style: date/month/year. Then show Mr. Fortna
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 will displays the day month and date in Spanish. Then show Mr. Fortna
This work by MrFortna.com is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.