A: JavaScript is rather syntax senstitive. That means you need to close all your parentheses, double quotes, and single quotes. You also need to end almost all lines with a semicolon, and also make sure that your code doesn't break onto subsequent lines. It may also be because you're a bad programmer.
Event Handlers
JavaScript is a scripting language that is embedded in Web pages and interpreted as the page is loaded. It can discover a lot of information about the HTML document it is in, and manipulate a variety of HTML elements. JavaScript works by assigning and working with variables and inserting them into functions, which can range from writing on the HTML page to changing images.
JavaScript scripts go both in the head and body of the document. When coding JavaScript, you must realize that it is line specific. One line will be read at a time. You cannot break most coding over several lines like you can in regular HTML.
We'll start with something easy, event handlers. Basically, these are short commands that tell the page to do something when a certain action is triggered.
SSH into GEOSC and go into your public_html directory. Pico a new file called tutorial12.html. Put all your regular tags onto the page (html, head, title, body, etc.).
Event handlers can go into many different tags. Each will trigger a predefined action when activated. Event handlers that JavaScript recognizes are the following: onClick, onMouseOver, onMouseOut, onDblClick, onMouseDown, onMouseUp, onKeyDown, and onKeyUp. Note the capitalization. JavaScript is based on the Java programming language, and so it follows many of the same programming conventions. Event handlers in both languages begin with a lowercase letter, and each subsequent word is capitalized. JavaScript is more lenient, but you should still capitalize properly to prevent unnecessary headaches.
In your body, create a 4x1 table. We will first apply event handlers to table cells.
To use an event handler, simply place it in the tag you want it to affect. If you want it to change the color of a table cell, you would have code like this:
Basically, the attribute that you want to be altered needs to go inside the quotes of the event handler. In this case, the event handler is onClick. The attribute we wanted to alter was the color of the table cell. The entire attribute went between the quotes. But, there are several differences between a regular attribute and one that we want to be altered for JavaScript.
First, all double quotes that we would have used needed to be converted into single quotes. Why? JavaScript reads your script left to right. When it comes to a double quote, it recognizes it as the start of a string. The next double quote it encounters is interpreted as the end of the string. If you were to have used double quotes around red, JavaScript would have read the string as "bgColor = ", red would be left hanging, and then you would have the empy string "". That doesn't make much sense, does it? It doesn't make sense to JavaScript either, so that's why you need to use single quotes in place of all double quotes for event handlers.
Secondly, notice the capitalization in bgColor. In HTML, you would just make everything lowercase. If you try that in JavaScript, nothing will happen. Again, this is just the way JavaScript works. "bgcolor" is like two words. Therefore, the second word needs to be capitalized.
Try applying the following event handlers to your table:
If you get any errors, make sure that everything is properly capitalized. You should now have a table with four cells, each that do a different thing based one what the mouse or keyboard is doing.
Underneath the table, add an image tag. Give it some event handlers, like this:
You can put all of this on one line. Note the order of the pictures. The initial and the "out" picture are the same. The only one that is different is when the mouse is over the picture. Having the image switch when the mouse passes over it works best when both images are the same size.
JavaScript event handlers can be placed in a variety of tags. The most useful will probably be table cells and images. You can experiment and see if they work on other tags.
Variables and Document Properties
Using event handlers can allow you to do some nifty stuff. But what if you want to make your page more dynamic? For example, what if you wanted the page to display information about the user's browser? We can't preprogram what to display in this case, since we don't know what browser or version number the user will be using. However, JavaScript will make this easy for us.
Before we start defining variables, we need something to store in our variables. It can be something as simple as "penguin" to something as complex as user input or information about the document.
To get information about a document, you would use something like this:
document.title
document.location
document.lastModified
These are all predefined. This means that when you call them, the browser knows automatically what to do with them. These lines will give you the document's title, it's URL, and finally it's timestamp.
In the body of your document, add a few lines that will give the use this information. To do this, you will need to utilize "document.write". This will simply write to the page whatever appears after it. Throw in a horizonal rule (<hr>) and then type in this code:
You should notice several things. Without the SCRIPT tags, the line is put down as regular HTML. You need to start the SCRIPT tag before your function and close it after your function so that the browser knows to interpret the line as script and not as text. You can use as many script tags in your document as you want. However, if you are going to use several in a row, you can group them all in one script tag. It is not necessary to open up a new script tag for all these scripts, just like it isn't necessary to open and close H1 tags around every word of a header.
document.write is structured in the same way as event handlers. Everything that you want to appear on the page must go between quotes. So why is document.title not in quotes? This is because we want to print the value of document.title on the page, and not the words "document.title". Anything that is not in quotes will automatically be interpretted as a variable. Since document.title is not in quotes, the browser returns the value that corresponds to the title of the page.
In order to connect the strings "Page Title: " and whatever document.title is, we need to place a plus sign between them. You can add another plus after document.title and put more text, but remember to put them in quotes if they aren't variables!
Notice also that we have a semicolon at the end of the line. This is how the browser knows that you have reached the end of a line of coding. You should place one at the end of any document.write on your page.
Try this line:
document.write(" URL: " + document.location +
" Last Modified: " + document.lastModified);
Notice that you can put HTML tags in document.write, and they will still be interpreted as HTML tags. Notice also that it is OK to break a command to the next line. You should do this between plusses. All your JavaScript will disappear if you break in the middle of a string (in which case the opening " is on one line and the closing " is on another line). JavaScript cannot understand this and will give you an error.
Also remember that if you are going to use whole HTML tags (like form) which have attributes in quotes, you will need to change the quotes to single quotes.
Let's say that we want to let the user know what browser he or she is using. The lines for that are similar:
navigator.appName
navigator.appVersion
They have the same structure as document.something, but since you are talking about the browser and not the document, you use navigator instead. appName and appVersion are properties of the browser, just like location and title were properties of the document.
We're very lazy and don't want to type out navigator.appName over and over again each time we want to use them in our documents. How can we make it easier for us? We could use copy and paste, but we can also use JavaScript to aid us.
The way to do this is to create a variable, store something in it, then use that variable somewhere else. In your head, type the following:
BName and BVersion are just names we made up. We could have just as well called them "a" and "b". But if we come back several months from now and look at our code, will we remember what a and b stand for? Probably not. But BName and BVersion give us a hint that we are talking about different properties of the browser.
Now, we are going to use the variable in our body. Go back to the script tags in your body and add the following lines:
document.write(" Browser Name: " + BName);
document.write(" Browser Version: " + BVersion);
It works the same, but if we want to use the browser name over again somewhere else, we can use the variable instead of typing out everything that's stored in there.
Functions
The hardest thing to do in JavaScript is to write functions. If you know some Java or have worked with programming languages before, you may not have quite as much trouble. It's OK if you haven't. Once you understand what a function does and how it is structured, you shouldn't have much trouble.
A function is simply a list of commands. These commands carry out some action. It could be something as simple as adding some numbers together or as complex as processing user input.
A function has the following structure:
function functionName()
{
Command to process
}
Like a variable, you tell JavaScript that you are defining a function by saying the word "function". Then, you give the function a name. This is always followed by parentheses, which are what tell the browser that you're defining a function. Even if they have nothing inside, they still need to be there. We'll do a test case later where we have something in the parentheses.
Note the use of squiggly brackets. These create a "block statement". Everything between the squiggly brackets is a part of the function. Note also that there is no semicolon after the function.
We will create a simple function that will tell us what page referred us to this page. If we clicked on a link that brought us here, the page should display what page we came from. If we got here just by typing the exact location of the document, we want the word "None" returned, since we didn't click anything to get here.
Go to your head and begin a function called refPage(), like this:
function refPage()
{
}
Now we will do some actual coding. What do we want this function to do? If there is a referring page, tell us what it is, otherwise return "None". How do we do this? We can use something called a conditional statement. We will use if...else. If something is true, then a certain action will be carried out. If that condition is false, the else part of the function will be carried out. So add this to your function:
if (document.referrer.length != 0)
return(document.referrer);
else
return("None");
document.referrer.length is a property of the referring page. If there is no referring page, it's value will be zero. If it isn't zero, then it will contain the URL of the referring page.
Our if statement is testing for inequality (!=). If document.referrer.lenth is not equal to 0 (meaning that there is a referring page), the function will return the URL of that page. Else, it will return the word "None".
You don't need to put squiggly brackets around whatever belongs to "if" or "else" unless there is more than one line after either one.
You can also write this function like this:
if (document.referrer.length == 0)
return("None");
else
return(document.referrer);
The difference is the order. In this statement, we are testing for equality (= assigns variables, so you need to use == to test for equality). If document.referrer.length is zero, meaning that there is no referring page, we want to return the word "None". Else, we want to return the referring page. Other tests you can use are <, >, <=, >=, ==, and !=. These are less than, greater than, less than or equal to, greater than or equal to, equal to, and not equal to.
Let's call this function (it works exactly the same way as calling variables):
document.write(" Referring Page: " + refPage());
Refresh your page and you'll see the word "None" on your page after referring page. Pico a quick file with a link to this lab. View the page, click on the link and view your referring page now. It should state the URL of the referring page.
User Input
The last thing we will cover with JavaScript is getting user input. We will do that by prompting the user to enter information.
To call a prompt, you simply need to use the word "prompt", followed by parentheses and two strings, one for the question and one for the default value. This prompt must be assigned to a variable if you want to use it again later in the page. Try putting this in your head after the refPage() function:
var name = prompt("Please give your name:", "");
if (name == null || name == "")
name = "User";
The variable we are creating is called "name", since we will be asking for the user's name. The first string is the question that will appear in the textbox. The second string is the default value. Even if there is no default value, you still need to put the quotes in. Since there is nothing between the quotes, you simply have an empty string.
What happens if the user clicks "OK" or "Cancel" without typing anything in? This will return either a blank string or a null value. We don't want the page to say "null's Page", do we? We want to give it a default value to go to in case the user doesn't input anything. That's what the if statement is for.
There are two conditions we want to test for. One of these is the null value, which is what will be returned if the user hits "Cancel". The second is the empty string, which is returned when the user hits "OK" without typing anything in. In either case, we want to store a predefined value into "name".
We could have just as well written two "if" statements testing for either condition. But once again, we are lazy and don't want to write another two lines. Since both conditions will yield the same results, we can test for both conditions at the same time. The way we tell the computer to write "User" if either one or the other condition is true is by using an OR connector, ||. If two conditions need to be true for an action to take place, we would connect them using &&, but that will not be the case here. Only one of the conditions needs to be true before "User" is saved into "name".
Now call the "name" variable at the top of your page, like this:
Refresh your page. When you do so, a prompt should pop up, asking you to enter your name. Try entering your name, hitting "OK" without typing anything, and hitting "Cancel". See what happens.
The final thing we will do is create a function that will be called at our command. Put the following code between the script tags in your head:
function popUp()
{
alert("Welcome " + name + "!");
}
Basically, when this function is run, it will pop up an alert box that will say "Welcome User!", or whatever you entered as your name.
We will place a button in our body that will call this function. Add a couple of breaks after the closing script tag in your body and add this line:
When the button is clicked, it will run the function popUp(). Try it and see what happens.
The important thing to remember from this lab is the following: Store variables in your head if you're going to be using them a lot later on. Use functions if there are one or more possibilities for data that can be stored in a variable. Functions are run when they are called.