
The Basics
This first script is meant to introduce you to the very basics of creating and placing a JavaScript on your page. During the deconstruction, you'll be given a few do's and don't's when writing JavaScript. The concept of this script is to use JavaScript to place text on a Web page. In this case, the text will be red.
Here's the first script:
<SCRIPT LANGUAGE="javascript">
document.write("<FONT COLOR='RED'>This Is Red Text</FONT>")
</SCRIPT>
The Script's Effect
This Is Red Text
Since this is the first script, it's fairly easy, to allow us to take some time here to discuss JavaScript in general.
What Is Java Script?
First off, it is not Java. It's easy to get confused and think that Java and JavaScript are one in the same. Not so. Java is a programming language developed at Sun Microsystems. JavaScript, on the other hand, was created by the good people at Netscape.
The two are similar in that they are both what are known as Object Orientated Programming (OOP). That means that you build smaller objects that make up the whole. For example, if the object is you. You have muscles, bone, tissue, organs, and skin to make up the complete object called you. That will make more sense as we go on. The main difference is that Java programming can create fully stand-alone events. A Java "applet" (so-called because it's a small application) may run on a Web page, but is actually a fully contained little program. In addition, Java cannot run as text. It must be "compiled" into what's known as a "machine language" before it can be run.
JavaScript is close to Java in that Netscape sort of pared down Java into an easier set of commands. JavaScript cannot stand alone. It must be running inside of a Web page, and the Web page must be displayed in a browser that understands the JavaScript language, like all Netscape browsers 2.0 and above.
Writing JavaScript
Remember that JavaScript is not
HTML! I am often asked if one is simply a different version of the other. Nope.
However, when writing JavaScript, you follow a lot of rules that are similar
to the rules of writing HTML.
First off, the JavaScript goes inside the HTML document. We'll get into placement
later. JavaScript is saved as text right along with the HTML document.
The major difference between the two is that HTML is very forgiving in terms of its shape. White space means nothing to HTML. How much space you leave between words or paragraphs doesn't matter. In fact, there's no reason why you couldn't write an HTML document as one long line. It doesn't matter.
The opposite is true in JavaScript. It does have a shape. There are some times when you can break the shape of a script, but not very many. For instance, the second line of the script in this primer looks like this:
That's its shape and it must remain in that shape. Let's say you paste this into a text editor with small margins. When you paste it, the margins jump the line down so it now looks like this:
You have altered the form and this script will now throw an error (we'll get into errors and fixing them in the next part of the lesson).
![]()
Editing JavaScript
Whether you're editing or writing script, you can not allow margins to get in the way. Always edit your work in a text editor that has no margins. I don't mean margins set to their widest point. I mean NO MARGINS. You should be able to write off of the right side of the text screen for miles. Doing it any other way is going to cause you problems.
Is JavaScript Case Sensitive? Yes.
![]()
Let's start at the top.
<SCRIPT LANGUAGE="javascript">
document.write("<FONT COLOR='RED'>This Is Red Text</FONT>")
</SCRIPT>
Here's the script again.
The first line of text looks like this:
<SCRIPT LANGUAGE="javascript">
That's HTML code to alert the browser that what immediately follows is going to be JavaScript script. That seems simple enough. All JavaScript's start with this exact command. But what about that LANGUAGE="JavaScript" deal? Do you really need that? Yes. There are other types of scripts, VBS and LiveScript for example. Using that LANGUAGE sub-command will keep it all straight in the browser's mind.
Since we're only dealing with three lines of text here, allow me to jump right to the end. This:
</SCRIPT>
...ends every JavaScript. No exceptions. Now, put that on a brain cell. That's the last time those two commands will be discussed.
Now we hit the meat of the script:
This script is simple enough that you can just about guess what each little bit does, but let's go over it anyway so that we're all speaking with the same common terms.
The script follows this path, the DOCUMENT (the HTML document) is announced. The document will be altered by WRITE-ing something to it. What will be written to the document is inside the parentheses.
Now some terms. The DOCUMENT above is what's known as an "object". The WRITE that follows, separated by a period, is what is known as the object's "method." So, the script is basically saying, take the object (something that already exists) and write something to it.
The text inside of the parentheses is called the method's "instances" or what will be done when the method is acted upon the object. With me so far?
Notice that what is inside of the parentheses is encased in quote marks. In HTML, those quote marks are not required. Here, they are. You must use them.
The text inside the quote marks is simple HTML. You should recognize the text
as a FONT command that will turn text red. Notice that the quote marks around
the HTML code are single quotes. They have to be. If you use double quotes,
then the JavaScript will think it has met the end of the line and you only get
part of your text written to the object. And that will throw an error.
Remember: Inside of double quotes... use single quotes.
So, did the JavaScript actually turn the text red? No. The HTML did that for you. All the JavaScript did was write the code to the page.
What You Have Learned
Alter the script above so that it will produce two lines of text, one red and one blue. But you must do this by writing more Javascript commands, not by simply adding more HTML to the instance. It will produce this on the page when you run it:
Here's a possible answer (this will open a new window )
Error Messages
You know what topic I've found missing from the myriad JavaScript books I've read? Error messages. I guess the assumption is that you'll get it all right the first time and never see one. Welcome to reality.
If you've ever attempted to write or install a
JavaScript on your Web pages, then you know these little jewels are part of
the fun. Just when you think you've got it right, boom! One of these pops up:
This part of the lesson is intended to tell you what to do when you encounter your own error messages. I've worked through thousands of them. If you start writing JavaScript, you'll get your share, too.
Please Note! In later versions of MSIE and Navigator, you may not get the box above. I guess the programmers felt there was a better way.
If you are using MSIE, the error message will first appear as a triangular sign in the lower left hand corner. There will be an exclamation point in the triangle. There will also be some text proclaiming there are errors on the page. Click on that triangle to get the error message we'll discuss in this tutorial. OR! If you want to get the error message box each time without clicking, go to the Tools menu, choose Internet Options. In Internet Options, click on the Advanced tab and make sure the line that reads: "Display a notification about every script error" is checked.
Then again, depending on how your system was configured when you got it, you may already be getting the box. You'll also note on the error box that you'll have to click the "Details" button to see the text describing the error.
If you are using a later version Netscape Navigator, then you'll get instructions in the status bar. If there in an error, you'll be told to type javascript: into the location bar. Then, you'll get the error and the text regarding it.
I don't understand the change either...but them's the breaks. Moooooving along...
The Error Message
There are basically two types of errors you can produce: Syntax errors and Run-Time errors. A Syntax error means that you've misspelled something or the JavaScript is not configured correctly. A Run-Time error means that you have used an incorrect command. Either way, they both mean the same thing. Somewhere, something's messed up.
Now, there are programs out there that will help you fix your errors, a process called "debugging," but I still prefer to do it by hand. It's actually easier than you think.
Fixing the Errors
It is said that the best way to fix errors is to avoid creating them. That's a great deal easier said than done. However, you can up your chances of getting fewer error messages by writing in a text editor that does not have margins. Also, allow each JavaScript command to remain on its own line. There's no need to break longer lines into two. In fact, doing that will probably throw errors. That said, I'll bet you get errors just about every time you start to play with this new language, so let's get into how to repair them.
The wonderful thing about a JavaScript error message box is that the little window that pops up tells you where and what the problem is. Look again at the error message above. It's a syntax error, meaning I have not configured the script correctly, and the error is on line 29. What's more, the error message is pointing at the problem area. Wouldn't it be great to get that in HTML?
The Error Line
When an error message denotes an error line, that line is counted down from the top of the HTML document, not the top of the JavaScript. For instance, the document below has an error in line 9. It's a syntax error because the instance was not allowed to close on the same line it started on. See how the parenthesis was jumped to the next line?
|
<HTML> <HEAD> <TITLE></TITLE> </HEAD> <BODY>
<SCRIPT LANGUAGE="javascript"> </SCRIPT>
</BODY> |
But why is the error on line 9? That's because you count from the top of the HTML document down, counting every line. Here's the document again, but this time with the lines counted for you.
|
(line 1) <HTML> (line 2) <HEAD> (line 3) <TITLE></TITLE> (line 4) </HEAD> (line 5) (line 6) <BODY> (line 7) (line 8) <SCRIPT LANGUAGE="javascript"> (line 9) document.write("text for the page" (line 10) ) (line 11) (line 12) </SCRIPT> (line 13) (line 14) </BODY> (line 15) </HTML> |
Notice that when you count the lines, you count all the lines, even the blank ones.
![]()
Now What?
Once you're actually at the line that has an error, you need to decide what to do. More times than not, if it's a Syntax error, the line has been chopped off early (truncated), something is misspelled, or you have used double quotes where a single quotes should go (unbalanced quotes).
If the error is Run-Time, then the command the error message is pointing at is a command that doesn't logically follow in the sequence. For instance, you call for a button by using a command that actually calls for a text box.
Multiple Errors
Nothing gives me heartburn faster than running a script and getting multiple errors. All you can do is sit while a whole slew of gray error boxes pile up on your desktop. I used to think multiple boxes meant there were actually multiple errors. Not always so.
JavaScript is an extremely logical language that likes things to move in a linear fashion. Let's say you have 10 errors throughout a long script. When the error messages pile up, the error that the computer found last in the script will be sitting on top of the pile of boxes. Do not go after that last error. It probably doesn't exist.
You see, the first error in the script may very well be creating all the other errors. So, fix the errors in sequence from the top of the HTML document to the bottom. Many times I've found a script that threw ~20 error boxes, but by fixing only the first error I solved all the problems.
So, fix the errors one at a time, from top to bottom. And each time you fix an error, run the script again. You might get 20 error messages, but only have to
fix one or two.
Something's Not Defined
This is also very common. This is a Run-Time error that means that something in the script doesn't jive quite right. The text, to the computer anyway, has come out of the clear blue sky. I always make sure the text wasn't created by jumping a line down too early. If that's not the case, I try erasing it. It can always be put back at another time. Typos occur. See if this isn't one of those typos. It happens more times than you'd believe.
There's not much more that can be said about error messages at this point. You now have enough knowledge to fix 99% of the problems that pop up. Just remember that getting error messages is actually a plus. If you didn't get them, then all you would have is a blank page with no suggestions about what the problem might be. They're quite helpful if you think about them in the right light.
What You Have Learned
Below there is a link to a page with a script. When you click on the link, the script will throw two errors. Your assignment is to fix the two errors so that the script runs. Now, you probably won't recognize some of the commands in this script, but that doesn't matter. The error boxes that appear will give you enough information to make this script run.
If the script runs correctly, the current date will display on the page. Again, each of these links will open a new window.
Hint: You may only get one error when you run it. The second error might then come after you fix the first.
Dates and Times
What's nice about writing JavaScript right to a Web page is all the stuff that already exists that you can grab and display.
In this lesson we'll talk about seven new methods: getDay(), getDate(), getMonth(), getFullYear(), getHour(), getMinute(), and getSecond(). Each of these already exists and can be grabbed and placed on your Web page. The problem is that these items are only methods. They need an object to act on and the document object won't do it... so we need to make one.
The Script
<SCRIPT LANGUAGE="JavaScript">
//This script posts the exact day and time you arrived
RightNow = new Date();
</SCRIPT>
document.write("Today's date is " + (RightNow.getMonth()+1)+
"-" + RightNow.getDate() + "-" + RightNow.getFullYear() + ".
You entered this Web Page at exactly: " + RightNow.getHours() +
":" + RightNow.getMinutes() + " and " + RightNow.getSeconds() +
" seconds")
By the way, the document.write line above should be all on one line. It is just written in sections above so you can see all the parts.
The Script's Effect
Today's date is 1-03-2007. You entered this Web Page at exactly: 13:44 and 22 seconds
Do not be taken aback by this script's size. It'll all make sense in a short while. Now allow me to once again drive a point into the ground. See the script's shape? That one line goes way off the end of the screen. That shape must be retained. Breaking that line into two will throw an error.
What's That // Thing?
As we move through the lesson, a few extra commands will be thrown in now and again. This is one of them. That double slash denotes a comment inside the script. It means that the text that follows will not be used in the process, but will rather be reprinted as-is. You can add as many of them as you'd like as long as each line starts with the double slash.
The Date and Time Methods
If you look at the script above, you'll see that the effect is created by asking the script to write the month, date, year,
hour, minute, and second to the page. The extra verbiage stuck in there just makes it obvious what you're looking at.
Each of the items were created using the method "getSomething()". Please notice the capitalization format. The "g" is lowercase then the first letter of the thing you are to get is capitalized.
First, remember that each of these items is numeric. They only return numbers.
Even the getDay() method that collects the day of the week returns a number,
one through seven.
Let's start with just the first one called for in the script above, the month.
Then we can start to break down how this pup works. As stated before, "getMonth()"
is a method. That said, we now must concern ourselves with what object "getMonth()"
is a method of.
It would appear from the script that again "getSomething()" is a method of "document". Not so. The method of "document" is "write". "getMonth()" is actually a method of the object Date. Again, look up at the script. "Date" is set aside in the command:
Here I am setting aside an object for the method getMonth() to work on. The
format is the same each time you use dates and times. You must create an object.
My object is titled RightNow. See that above? Now, I could have called
it Zork or Fred for all the browser cares. It doesn't matter as long as the
object is given an original name that isn't found in JavaScript. Use this format
every time you use dates or times.
If that seems backwards to you, it does to me, too. It seems like it should
be new Date = RightNow, but it isn't. You're learning a new language and you
have to play by its rules.
The command above is saying: RightNow is the object that represents a
new Date();. The date has to be new. That way you get a new date every
time the page is reloaded or entered. Without the new command, the date would
remain static.
Also notice the semicolon at the end of the line. That acts as a statement terminator. It denotes that one complete line of JavaScript has ended. Without it, the browser thinks the line just continues on to the next. Error.
Hooray! We have our object so that our "getMonth()" method can act upon it. We want this month to be printed on the page so we need to have a document.write() statement in there somewhere. We also know that what appears in the parentheses is printed on the page, so let's put it together following a logical process:
Look up at the full script again. That long line of text doesn't look so tough now. It's simply the "RightNow" object followed by the next "getSomething()" method. I separated each with a hyphen. Remember, the hyphen is to be printed so it needs to be in quotes. Then each of the parts are connected using a plus sign (+).
Adding Spaces
This is a little trick you'll need to know. No matter how many spaces you put before or after the plus signs, it doesn't translate in the printed result. It all runs together. So, if you want spaces, you need to add them in the text section. Example:
See how I added two spaces before the end quote? That will translate to two spaces when the script prints it to the page. Remember: This is not HTML. There are new rules for spaces and how to add them to your page.
Building the Long Line
I won't go through it all, because you probably have the swing of it by now. I'll do the full date alone. It looks like this:
document.write("Today's date is " + (RightNow.getMonth()+1)+
"-" + RightNow.getDate() + "-" + RightNow.getFullYear() + ".
You entered this Web Page at exactly: " + RightNow.getHours() +
":" + RightNow.getMinutes() + " and " + RightNow.getSeconds() +
" seconds")
Just continue to follow this same format and the script will print out exactly what you want. So, now you can tell everyone what time it is. But as Chicago said... Does anybody really know what time it is? Does anybody really care?
A known concern: I stated this above, but I wanted to hit it one more time. In one of the more interesting bugs of JavaScript, you may have noticed above that the month is off by one when you just use the getMonth() alone. Why? Remember that the numbers returned are in JavaScript and JavaScript likes to count up from zero. Strange, yes, but that's what it does. Thus January is seen as "0" and every month after is one down.
So, what do you do? Well, you add 1, of course! The code is a little tricky. It involves making a couple of variables. That's where you assign a name to something . You assign "new Date()" a name just like you did above. Then you assign a name to the code that calls for the month. I called it "mpo" below (to stand for Month Plus One). Then you add one to that name. I called it "mpo1" below. It sounds confusing, but it's not. Here's what it looks like:
And here's what you get:
Today's Month is 5
I'll bet that's the correct month, right? I did it above by simply adding one and surrounding the whole thing in ( and ).
What You Have Learned
This one isn't so tough. What I would like is for you to write a script that shows the date separated by slashes on your welcome page. I'd like the welcome text printed in green. Don't worry about the numbers you'll learn about that when you take the Internet Programming - JavaScript Class. This will wrap it up for the introduction to JavaScript. I hope you have had fun this week.
Material for this lesson has been adapted from the HTML GOODIES site created by Joe Burns located at http://www.htmlgoodies.com/