Sunday, December 9, 2007

Submitting forms

Submitting forms

What different possibilities do exist for submitting the contents of a form? The easiest way is to submit the form input via e-mail. This is the method we are going to look at a little closer. If you want to get feedback without e-mail and want the server to handle the input automatically you have to use CGI at the moment. You would need CGI for example if you wanted to make a search engine like Yahoo- where the user gets a result quickly after the form input. He does not have to wait until the people maintaining this server read the input and then look up the information requested. This is done automatically by the server. JavaScript does not have the functionality to do things like this. Even if you want to create a guestbook you can't make the server to add the information automatically to an existing HTML- page with JavaScript. Only CGI can do this at the moment. Of course you can create a guestbook with the people answering via e-mail. You have to enter the feedback manually though. This is ok if you don't expect to get 1000 feedback mails a day.

This script here is plain HTML. So no JavaScript is needed here! Only, of course, if you want to check the input before the form is submitted you will need JavaScript. I have to add that the mailto- command does not work for every browser- but the newer browsers support it.

Do you like this page?

Not at all.

Waste of time.


Worst site of the Net.


You will get the feedback through e-mail by doing this. The only problem is that you will receive a mail that might seem very cryptic at the first glance. Sometimes all spaces are filled up with '+' and sometimes they are filled up with '%20'. So+this+might+look+like+this. There are some parser programms out on the Net, I believe, which will put the received mail in to a nicer format.

There is another nice thing so you can make your form elements a little bit more user-friendly. You can define which element is in focus at the beginning. Or you could tell the browser to focus on the form where the user- input was done wrong. This means that the browser will set the cursor into the specified form- element so the user does not have to click on the form before entering anything. You can do this with the following piece of script:

function setfocus() {

document.first.text1.focus();

return;

}

This script would set the focus to the first text- element in the script I have shown above. You have to specify the name of the whole form - which is here called first - and the name of the single form element - here text1. If you want to put the focus on this element when the page is being loaded you can add an onLoad- property to your tag. This looks like this for example:

Last changed: 11.May'96

©1996 by Stefan Koch


Validating form input

Validating form input

Form input is very important for some Web- pages. The form input is often sent back to the server again. JavaScript has got the functionality to validate the form input before sending it to the server. First I want to show you how forms can be validated. Then we will have a look at the possibilties for sending information back with JavaScript or HTML.

First of all we want to create a simple script. The HTML- page shall contain two text- elements. The user has to write his name into the first and an e-mail address into the second element. You can try this scripts in the online version of my tutorial.

Concerning the first input element you will receive an error message when not entering anything. Any input is seen as valid input. Of course, this does not prevent the user from entering any wrong name. The browser even accepts numbers. So if you enter '17' you will get 'Hi 17!'.

The second form is a little bit more sophisticated. If you try to enter a simple string - your name for example it won't work (unless you have a @ in your name...). The criteria for accepting the input as a valid e-mail address is the @. A single @ will do it - but this is certainly not very meaningful. Every Internet e-mail address contains a @ so it seems appropriate to check for a @ here.

What does the script for those two form elements and for the validating look like? Here it goes:

Enter your name:

Enter your e-mail address:

First have a look at the HTML- code in the body- section. We just create two text elements and two buttons. The buttons call the functions test1(...) or test2(...) depending on which button is pressed. We pass this.form to the functions in order to be able to address the right elements in the functions later on. The function test1(form) tests if the string is empty. This is done via if (form.text1.value == "")... . 'form' is the variable which receives the 'this.form' value in the function call. We can get the value of the input element through using 'value' in combination with form.text1. In order to look if the string is empty we compare it with "". If the input string equals "" then no input was done. The user will get an error message. If something is entered the user will get an ok.

The problem here is that the user might enter only spaces. This is seen as a valid input! If you want to, you can of course check for these possibilities and exclude them. I think this is quite easy with the information given here.

Now have a look at the test2(form) function. This function again compares the input string with the empty string "" to make sure that something has been entered. But we have added something to the if- command. The || is called the OR- operator. You have learned about it in part 6 of this introduction. The if- command checks if either the first or the second comparison is true. If at least one of them is true the whole if- command gets true and the following command will be executed. This means that you will get an error message either if your string is empty or if there isn't a @ in your string. The second operation in the if- command looks if the entered string contains a @.

Operators

Operators

Now we will have a look at different operators you might use in JavaScript. Operators are a powerful technique to shorten and improve your script. For example you want to test if a variable x is larger than 3 and you want to see if it is smaller than 10. You might want to write it this way:

if (x>3)

if (x<10)

doanything();

The function doanything() is called if x>3 and x<10.>

if (x>3 && x<10)>

The && is called AND- operator. Then there is an OR- operator. You can use this for example if you want to check if one variable x is equal 5 or another variable y is equal 17:

if (x==5 || y==17) doanything();

The function doanything() is called when x==5 or y==17. It is also called if both comparisons are true. Comparisons are done via the == operator in JavaScript (Of course there are also <,>,<= and >=). If you know C/C++, this is the same. A single = is used to store a value in a variable. (If you know Pascal this may be a little bit confusing. Assigning a value to a variable is done in Pascal via := and comparisons with a single =)

If you want to see if a variable does not equal a certain number, this might get a little bit complicated without operators. This is done with a simple !=. So this would look like this for example: x != 17.

There are many more interesting operators which can make your programs more efficiently. Look at the documentation provided by Netscape to get a full overview of all operators you can use in JavaScript.

Last changed: 11.May'96

©1996 by Stefan Koch

Creating a new window when a link is taken

Creating a new window when a link is taken

Another often seen problem is how new pages can be loaded to a new window. The window shall pop up when the user clicks on a link. You just have to add the target- property to your tag again. This looks like this:

Go!

Loading two pages with one mouse click

Loading two pages with one mouse click

I receive a lot of mails about the problem how two pages can be loaded with only one mouse click. Basically there are three different solutions to this problem. The first possiblity is to create a button which calls a function when the user presses it. This function loads the two pages into different frames or opens new windows. This is not too difficult if you have a look at our examples in the other parts of this introduction. We have all elements we already need.

We create three frames. The first one is used for the button. The first html-page is just needed for openening the frames and giving names to them. This is nothing new since we used this technique in part 3 in order to work with frames. I'll show it to you anyway. (I don't know whether this happens to you as well- but everytime an author of a computer book thinks that something hasn't got to be printed because it is so easy - this is exactly the part I'm having trouble with. So here we go:)

frames2.htm

Frames

loadtwo.htm is loaded to the first frame. This is the frame with the button.

loadtwo.htm

The function loadtwo() is called when the button is pressed. Two strings are passed to the function. If you look at the loadtwo() function you see that the second frame fr2 loads the page that is defined by the first string in the function call. If you have different buttons opening different pages you can reuse this function. You only have to pass the different URLs (addresses) of the pages.

The second technique uses hyperlinks. Some examples floating around the Internet have something like this:

This technique seems not to work on all platforms. So you better don't use it. I'm not sure if it is supposed to work at all - but we don't have to worry because there is another method how we can implement this. We can call a JavaScript- function the following way:

My Link

This is really easy and seems to work fine on all browsers. You just have to write javascript: and then the name of your function as your 'link'. If you call the 'loadtwo()'- function from the example above you can update two frames with one single click on a hyperlink. You should always use this technique if you want to call a function with a click on a link.

The third technique for loading two pages on one mouse click can be combined either with buttons or normal hyperlinks. We could do this with the second technique shown above but this approach here might be more appropriate sometimes. What we can do is to load one HTML- page to one frame. This is done by

Click here!

We know this already. What we do now is to add a onLoad property to the loaded file. The getfr2.htm file could look like this:

bla bla bla

Of course you have to add this to every document that is loaded into the second frame.

History- functions: Creating 'back' and 'forward' with JavaScript

History- functions: Creating 'back' and 'forward' with JavaScript

Now we're looking at a script which lets you navigate through different documents. What I'm talking about is the back() and forward()- function. If you have a back- link on your page this isn't the same as the back- button in the Netscape- Navigator. For example I have got some back- links which work like normal links but I know that the user probably comes from that certain page I'm linking to. The back- button provided by the Netscape Navigator goes one step back in your history list. You can do this with JavaScript as well. Just take this link in order to get back again! The script I used here is shown below:

You could also write history.go(-1) and history.go(1).

Last changed: 11.May'96

©1996 by Stefan Koch

Clearing a window ot frame

Clearing a window ot frame

I have written a small game yesterday. I have encountered a problem you might have got as well. If you want to clear a window or frame you look into the documentation by Netscape and see that JavaScript knows the function 'document.clear()'. But if you implement this function nothing happens! The function document.clear() seems to be broken on every platform. Gordon McComb gave me the following script which clears the window as I wanted it.

document.close();

document.open();

document.write("

");

You don't have to write document.write("

");. It is only important that you send anything to the window. This works fine with frames as well.

Working with arrays

Working with arrays

One important programming technique is the use of arrays. Most programming language support them in a certain manner. Maybe you have already come to a point where arrays would help you further. But if you looked through the documentation provided by Netscape you realized that nothing is said about arrays. The problem is that arrays do not exist in JavaScript! But I can show you a work around of course!

First, what are arrays? You could say that arrays are many variables bound together. Let's say that you want 10 variables. You could begin with the variables a, b, c ... But this is really complicated. Especially if you want to store 100 or more variables. If you have an array which is called 'MyArray' and it has got 10 elements, you could address the different elements with MyArray[1], MyArray[2], MyArray[3]... (many programming languages start with the 0 as the first element- but we want to have the 1 as first element because this is the way we use it later in JavaScript). So if you want to keep the number 17 in the first element you have to write MyArray[1]=17. You see that you can work with arrays the same way as with normal variables. But there are some more features. If you want to store the number 17 in every element you can write it this way:

for (var i=1;i<11;i++)>

The for- command tells the computer how often the next command is going to be executed. The for- loop starts with i= 1. First the computer gets the command MyArray[1]= 17. After this i is incremented by 1 and then the command is MyArray[2]= 17. i is incremented until it has the value 10. (The expression i<11>

Now I will show you a function to initialize arrays. This function was discussed in the JavaScript Mailing list.

function initArray() {

this.length = initArray.arguments.length

for (var i = 0; i <>

this[i+1] = initArray.arguments[i]

}

You don't need to understand this function. You only have to know how to use this function. If you want to create an array with three elements you just write: var MyArray= new initArray(17,18,19). 17,18,19 are assigned to the elements 1,2,3. You could as well write strings to your array. So you don't have to matter which type is used! var heyho= new initArray("This","is","cool"). Mixing different types is no problem at all: var Mixedup= new initArray(17,"yo",103).

Here is the output of the following code:

Element No. 1: 17

Element No. 2: yo

Element No. 3: 103

This is the script for the output:

Programming a scroller

Programming a scroller

As you already know how to write to the statusbar and how the setTimeout- function works the scroller will be easy for you to understand. In the online version you have the possibility to watch this scroller code in work. Have a look at the script:

Here goes your cool page!

This script uses the same functions (or parts of it) we already used above. The setTimeout(...) 'tells' the timer to call the scroll() function when the time is up. The scroller will move one step further. At the beginning there are a lot of calculations but these are not too important for understanding how the script works. The calculations are there for getting the position where the scroller ought to start. If it is just at the start the script has to add some spaces in order to place the text right.

I told you at the beginning of this part of my introduction that scrollers are not very popular or if they are still popular they won't be it very long anymore. There are some reasons. I list several here but there are certainly more. If you see this effect for the first time it might be quite nice but looking at it the 1 million and second time it is not that fun anymore. Well, this is no good argument indeed because this affects nearly every cool trick used in your pages. There are more severe problems. What I don't like is that it changes the speed when you move the mouse (It gets faster!). At least it does that for me. This effect gets a lot stronger when you want to make the scroller little bit faster by changing the setTimeout- value. Maybe there is a way around this problem. But the worst is that if you let this script run some time you get an Out of memory error. And this is really ugly. It seems to be a problem of the Netscape Navigator 2.0. Maybe a higher version will have this bug fixed.

There are many other routines out there on the Net. I've seen some scrollers writing the text to a frame. Programming this shouldn't be too difficult with the techniques described in this tutorial.

Last changed: 11.May'96

©1996 by Stefan Koch


Working with timers

Working with timers

You know already the onMouseOver- property from part 2 of my tutorial:

Don't you hate it that the statusbar does not erase the text when the mousepointer does not point on the link any longer? I have quite a simple solution. We just write a small function which uses the same technique to erase the statusbar as shown above. But how can the erase- function be called? We don't have a method or property which we can use for detecting if the mouse pointer is moving from a link. Setting a timer is the solution.

link

You will recognize many parts of this script. The moveover(txt) function is just the statbar(txt) function after some copy/paste work on it! Nearly the same happend to the erase() function. In the of the HTML- page we create a link with the known onMouseOver- property. Our moveover(txt) function is called with the string 'Disappearing!' being passed over to the txt variable. The window.status gets the contents of txt. This the same thing as in the statbar(txt) function. The setTimeout(...) function call is new though.

This function sets a timeout. Who was expecting this? The setTimeout(...) function defines how long the timer is going to run and what will happen when the time is over. In our example the erase() function is called after 1000 milliseconds (that's a second for all math- cracks out there). This is a phantastic feature! Your function moveover(txt) function is finished after the timer is set. The browser calls the function erase() automatically after 1 second. (Already thinking of a page telling the user: If you don't do this your harddrive is going to be destroyed in 10 seconds! ???) After the timeout is finished the timer does not restart again. But you could of course call it again in the erase() function. This leads us directly to the all-over liked scrollers.

Writing to the statusbar

Writing to the statusbar

Now I want to show you how to write text to the statusbar (the bar on the bottom of your browser where the URLs are shown) and of course I will explain how a scroller works- although they are already hated in the JavaScript scene (I tell you why later on). At first how is the statusbar 'addressed' ? This script shows you how one can write a simple text to the statusbar:

We create two buttons which call both the function statbar(txt). The txt in the brackets shows that the function gets a variable passed over from the function call. (I called this just txt- it could as well be anything totaly different.) When you look at the

tag where the buttons are created you can see that the function statbar(txt) is called. But we don't write txt there. We just put the text there we want the browser to show in the statusbar. You can see it this way: The function is called and defines the variable txt- it gets the 'value' you passed over by the function call. So when pressing the 'Write!' button the statbar(txt) function is called and txt stores the string 'Hi! This is the statusbar'. You can now use the variable txt as usual.

This method of passing variables to a function makes the function very flexible. Look at the second button. It calls the same function. Without variable passing we would need 2 different functions. Now what does the function statbar(txt) do? Well this is simple. You just write the contents of txt to the variable window.status. This is done by window.status = txt;. Writing an empty string ('') to the statusbar erases it. Notice that we have to use these single quotes ' because we use double quotes " for defining onClick. The browser needs to know which quotes belong together- so you have to alternate with single and double quotes. I think this is quite clear.

JavaScript and frames

JavaScript and frames

Many people asked me how JavaScript and frames work together. To use frames with JavaScript you got to have Netscape Navigator 2.0 (or higher) at the moment. There are some other browsers which support frames by now- but they usually do not support JavaScript. But I think that it won't take too long until there are further browsers which support frames and JavaScript.

First, I want to tell you a little bit about frames. Many documentations for HTML do not contain anything about frames because frames are quite new. Using frames you can 'divide' your window which displays the HTML- pages into several parts. So you have some independent parts in your window. You can load different pages to the frames. A nice thing is that these frames can interact. That means they can exchange information between each other. For example you could create 2 frames. One with your normal HTML- page and one with a toolbar. The toolbar could contain buttons for navigating through your normal HTML- page. The toolbar will always be visible even when another HTML- page is loaded in the other frame. At first I want to show to you what this will look like:

Here is the HTML- script for frames:

Frames

At first you tell the browser how many frames you want to have. This is defined in the tag. Writing rows to it the browser will divide the given space into rows. You can create different columns by using cols instead of rows. You can use several tags as well. Here is an example provided by Netscape:

This will create two columns and the second column is divided into 3 equal parts. The 50%,50% in the first tag tells the browser how big the frames shall be. You can give names to your frames. This is important for the use with JavaScript. In the first example above you can see how frames get their names. Using the tag you tell the browser which HTML- page to load.

Let's get to the next example. This will show a window with 2 frames. You can click on some buttons in one frame in order to write some text to the other frame. Here goes the source:

To create the frames you'll need (frames.htm):

Frames

Here is the source for frame1.htm:

This is our first frame!

And now frame2.htm:

This is our second frame!

Wow! These scripts get longer and longer! What is done here? The user loads the first file (frames.htm). This creates the frames and loads the HTML- file frame1.htm to the first frame (named 'fr1') and frame2.htm to the second frame (called 'fr2'). This is plain HTML until here. As you can see the first script frame1.htm contains some JavaScript functions. But they are not called in the first script. Are these functions not needed at all? Am I just too lazy to delete the useless functions? Although I'm certainly the lazy type of guy these functions are needed in fact. They are called by the second script frame2.htm! We create some buttons in this second script like the way we did in the first part of this introduction. The onClick- property is familiar as well. But what does the parent.fr1... mean?

If you are familiar with objects then this is not new to you. As you have seen above the frame1.htm and frame2.htm are called by the file frames.htm. Frames.htm is called the parent of the other two frames. Consequently the two new frames are called child- frames of the frames.htm. You can see there is a kind of hierarchy which gives a certain interrelation between the different frames. I try to show this idea to you with the help of a small 'graphic':

You can extend this concept of course. You can create some 'grandchildren' (if you want to call it like this- it is not the official expression!). It looks like this:

If you want to index anything in the parent- frame from frame2.htm you just put parent. before the function you call. Addressing the functions defined in frame1.htm from the parent- frame can be done by putting fr1 before the function- call. Why fr1? In your script for the parent- frame (frames.htm) you created the different frames and gave them different names. I chose fr1 for the first frame. The next step is easy. How is the first frame called if you want to address it from frame2.htm (which is kept in the second frame called fr2)? As you can see in my awesome graphic there is no direct connection between frame1.htm and frame2.htm. So you cannot call functions directly from frame2.htm defined in frame1.htm. You have to address it via the parent- frame. So the right index is parent.fr1. If you want to call the function hi() from frame2.htm you just write parent.fr1.hi(). This is what is done in the second script in the onClick- property.

If you have created some frames and someone takes a link the frames do not disappear. This is ok if the user 'stays on' your page. You could create a menubar which is shown in one frame all the time for example. But if the user jumps to another page in the Internet your menubar might not be wanted anymore. So how can you delete the frames once created?

Just add TARGET="_top" to your tag. This looks like this then:

if you don't want to stare at my page anymore

Of course, you have to add TARGET="_top" to every link that leads 'outside'. If every link in your page leads 'outside' you can also write to the head of your HTML- page. This means that every link in the page erases the frames.

Last changed: 18.March'96

©1996 by Stefan Koch

Hints and Bugs concerning document.write and images

Hints and Bugs concerning document.write and images

Please note this: When writing something to a window you should always put a
after the last text you write to a window. Otherwise you probably don't get to see the last row of your text. This happens because the browser only writes out complete lines - and if there is no end of the line it waits for more to come. Another important thing is this: If you want to insert any images into a new window be sure to put the height and width properties to the tag. Otherwise you won't see any pictures or your pages crashes somehow. This may cause some very strange problems where you don't expect the image to be 'responsible' for. So always write something like this so you won't get any trouble:

Last changed: 11.May'96

©1996 by Stefan Koch


Creating windows

Creating windows

Creating windows is a great feature of JavaScript. You can build new windows. Load a HTML- document. Navigate through the Internet- all with JavaScript. I'm going to show you how we can open a window and write something to it. If you push this button you will get to see what I'm going to explain to you next. Breaking up with traditions I didn't write Hello world! to the page...

Here is the source:

As always you can see the button which calles a function. The function WinOpen() creates a new window by calling the method open. The first quotes contain the URL of the page. Here you can put the address of a HTML- document which you want to load. If you leave it blank no page is loaded and you can write to it with JavaScript! The next quotes specify the name of the window. Here you can write nearly anything- this has no effect on our examples right know. But you will get an error message if you write Display Window (with a space between the two words - Netscape tells you something different in their information- but I sat half an hour because I could not find an error!) The next quotes specify the properties of the window. This is really interesting. You can tell if you want a toolbar, scrollbars... If you write toolbar=yes then you will get a toolbar in your window. There are some different properties listed below which you can change. You can specify every possible property. You have to write them the way shown above. And with no spaces between! Here is what you can change on your page:

toolbar

location

directories

status

menubar

scrollbars

resizable

copyhistory

width=pixels

height=pixels

For 'pixels' you have to write the number of pixels. This way you can tell the browser how large your window should be. After you have opened your window and called it msg (stands in front of the open- method), you can now write to your window. Here you can write normal HTML- code! This is really a great thing. You could build a HTML- document using the form input a user gave you in the document before. You could make a page where a user has to write his name to a form and then a new HTML- document is created containing his name! Some months ago this was only possible with CGI- Scripts!

Random numbers

Random numbers

A common problem is how you can use random numbers in programming and scripting languages. At the moment the random- function in JavaScript does not work but it soon going to be implemented, I believe. But at the moment you have to work with some tricks. Well, it is not really a trick. This is a really common way almost any compiler I can think of uses to calculate random numbers. Yes, it calculates it.

You take the time and date of your machine and manipulate it somehow. I believe the final JavaScript language will use this method (or a kind of it) as well. As I told you above the time is just a large number. You can use this number and make some calculations with it. For example you could calculate the sine from it and take the absolute value. This will get a number between 0 and 1. As the time changes every millisecond you won't risk to get the same number twice (when calculating them fast behind each other). If you want to calculate many random numbers in a short time you should not use sin() alone. Then you would get numbers following a sine- curve! This is not really random. But if you want to calculate a random number and let's say in 20 seconds again- this is a great function to do this.

Here is an sample output of this function. The number changes with every reload of the WWW-page:

This is a random number: 0.91936074496779396

Here is the code for this example:

Of course the random- function shown here isn't great for all puposes. It is just that you get a basic idea about how they work. Here I will present a function which I got from Maynard Demmon. You just have to set the limits variable to the value you need - 100 for example. And you will get a 'good' random value between 0 and 99. Here is the code:

function random() {

today = new Date();

num = today.getTime();

num = Math.round(Math.abs(Math.sin (num)*1000000)) % limits;

return num;

}

More date- functions

More date- functions

Now I want to show another example to you using the time and date methods. You already saw the lastModified property working. Now we are going to print the local time to our document. This method uses the time and date of your machine- so if you got the machine- date set to 5/17/1983 you will get the wrong date by this method as well. So this is not a time and date kept by the Internet (or something like that).

The following example prints out something like this. The time and date in the WWW- document is the real time and date (if the user has set the system- clock right of course).

The time now is: 0:13

The date is: 5/11/96

Here is the code:

At first we are creating a date variable. This is done by today=new Date(). If we do not specify a certain time and date the browser uses the local time and puts it into the variable today. Notice that we do not have to declare the variable today anywhere. This is a difference to Java and most other programming languages where you have to specify your types you want to use before you use them. We have created a time object which keeps the local time and date.

Now we can simply write its contents to the document. You have to write today before each get...- method. Otherwise the browser would not know which object to refer to. The getMonth() method returns a number between 0 and 11 (0 standing for january and 11 for december). So we have to add 1 to the number returned to get the right month. An interesting thing you could think of is to create a date - for example the date when you created a document. Then you could calculate how many days later somebody is reading your document. And if it is more than 10 days old you could tell him: Hey, this is really old- don't read it!

For this you will need the date of today as shown in the example above and the creation date. You can set a date while creating a date object. This would look like this:

docStarted= new Date(96,0,13)

You have to specify the year first, then the month (remember to decrease the month by one!) and then the day. You can also specify the time:

docStarted= new Date(96,0,13,10,50,0)

The first numbers are still the date. They are followed by the hour, the minutes and the seconds.

I have to tell you that JavaScript does not have a real date type. But as you see you can work with dates quite nice. This works because dates are represented by the number of milliseconds since 1/1/1970 0:0h. This sounds quite complicated but this is a common method for representing dates on computers. But you don't have to bother about this. You just have to care about the functions and this is not difficult at all. I just wanted to tell you so you don't think I tell you anything wrong.

Working with dates

The onMouseOver- property

In the online version of this document you can see a link where you can move your mousepointer over. This causes a text to be written to the statusbar. You can combine this with other JavaScript functions as well. Another example shows that you can call an alert- message box when moving over a link. Here is the code for the first example:

The only thing you have to do is to add the onMouseOver- property to your - tag. The 'window.status' will allow you to write things to the statusbar of your web-browser. As you can see you have to alter with the quotes. You cannot use " all the time, because otherwise JavaScript is not able to identify the string you want to print to the statusbar. After the string you have to write ;return true.

The second example uses JavaScript by calling the alert- function. Here is the code:

link

This is quite easy. It uses the onMouseOver- method and the function hello() is called when this event occurs.

Working with dates

Working with dates

I think the next thing is quite nice as well. We're going to implement a date function into our script. So if you creat a HTML- page you can make the client print the last change of the document. You do not have to write the date to the document though. You simply write a small script program. When you make some changes in the future, the date changes automatically.

This is a simple HTML- page.


Last changes:

At the moment this property seems not to function on every machine. Some servers show only the date 1/1/1970. There seem to be some problems with this function. We have to wait for the next update and hope that it works then properly on every machine. But you have to test this on your own machine - on some it seems to work fine.

As I already said things are moving really fast today. So it would not be amazing if next week there was a major change to JavaScript! So you always have to watch out for further changes as this language is quite young. Please understand that some things told here might change as well. But I think that the basic principles are going to stay the same.

Last changed: 10.May'96

©1996 by Stefan Koch

Let's get started

Let's get started

Now I want to show some small scripts to you so you can learn how they are implemented into HTML- documents and to show which possibilities you have with the new scripting language. I will begin with a very small script which will only print a text into an HTML-document.

My first JavaScript script!


This is a normal HTML document.



Back in HTML again.

You are just reading the 'offline'- version of this document. I have an online version of this tutorial on my homepage at http://rummelplatz.uni-mannheim.de/~skoch/js/script.htm. There you can see the results of the JavaScript code directly. You can try out the JavaScript examples immediately. I will present the results of the examples here as good as I can. But I recommend that you have a look at the examples online as well - so you get an idea of what is possible in JavaScript.

The output of the first example is just this text:

This is a normal HTML document.

This is JavaScript!

Back in HTML again.

I must admit that this script is not very useful. You could write this in HTML much faster and shorter. But what I wanted to show is how you have to use the tags. You can use these tags in your document wherever you want. I really don't want to bother you with such stupid scripts any longer. So we will procede to functions. This is not hard to understand either but, believe me, it is much more useful! Functions are best declared between the tags of your HTML- page. Functions are often called by user-initiated events. So it seems reasonable to keep the functions between the tags. They are loaded first before a user can do anything that might call a function. Scripts can be placed between inside comment fields to ensure that older browsers do not display the script itself.

This script creates a button and when you press it a window will pop up saying 'Hello!'. Isn't that great? So, what is going on on this script? At first the function is loaded and kept in memory. Then a button is created with the normal

tag (HTML). There is something quite new with the tag. There you can see 'onClick'. This tells the browser which function it has to call when this button is pressed (of course, only if the browser supports JavaScript). The function 'pushbutton()' is declared in the header. When the button is pressed this function is executed. There is another new thing in this script- the 'alert' method. This method is already declared in JavaScript - so you only have to call it. There are several pre-defined functions available in JavaScript. You will learn about many more in this tutorial. You can find a complete description about all functions in JavaScript at the Netscape- Site. I think that this list is getting a lot longer in the near future. But right at the moment there are already some cool things we can do with the given methods. (I don't think the alert- Method is thought to be used this way - but we're only learning. And this way it is quite easy to understand. I hope you will excuse me...)

We got quite far by now. In fact we have a lot of possibilities just by adding functions to our scripts. Now I will show how you can read something a user has inserted into a form.

Please enter your name:

We have some new elements implemented in this script again. At first you have certainly noticed the comment in the script. This way you can hide the script from old browser- which cannot run scripts. You have to keep to the shown order! The beginning of the comment must be just after the first tag. In this HTML- document you have got a form element where a user can enter his name. The 'onBlur' in the tag tells the client which function it has to call when something is entered into the form. The function 'getname(str)' will be called after 'leaving' this form element (for example clicking besides it) or by pressing enter after entering something. The function will get the string you entered through the command 'getname(this.value)'. 'this.value' means the value you entered into this form element.

How can JavaScript scripts be run?

How can JavaScript scripts be run?

The first browser to support JavaScript was the Netscape Navigator 2.0. Of course the higher versions do have JavaScript as well. You might know that Java does not run on all Netscape Navigator 2.0 (or higher) versions. But this is not true for JavaScript - although there are some problems with the different versions. The Mac- version for example seems to have many bugs.

In the near future there are going to be some other browsers which support JavaScript. The Microsoft Internet Explorer 3.0 is going to support JavaScript. JavaScript- enabled browsers are going to be wide spread soon - so it is worth learning this new technique now. You might realize that is really easy to write JavaScript scripts. All you have to know is some basic techniques and some work- arounds for problems you might encounter.

Of course you need a basic understanding of HTML before reading this tutorial. You can find many really good online ressources about HTML. Best you make an online search about 'html' at Yahoo (http://www.yahoo.com) if you want to get informed about HTML. (These online- documents are often more up-to-date than books. The Internet is moving quite fast these days...)

What is the difference between JavaScript and Java?

What is the difference between JavaScript and Java?

Although the names are almost the same Java is not the same as JavaScript! These are two different techniques for Internet programming. Java is a programming language. JavaScript is a scripting language (as the name implies). The difference is that you can create real programs with Java. But often you just want to make a nice effect without having to bother about real programming. So JavaScript is meant to be easy to understand and easy to use. JavaScript authors should not have to care too much about programming.

You could say that JavaSript is rather an extension to HTML than a separate computer language. Of course this is not the 'official' definition but I think this makes it easier to understand the difference between Java and JavaScript. You can find further information about both Java and JavaScript at http://www.gamelan.com.

What is JavaScript?

What is JavaScript?

JavaScript is a new scripting language for Web- pages. Scripts written with JavaScript can be embedded into your HTML- pages. With JavaScript you have very many possibilities for enhancing your HTML- page with interesting elements. For example you are able to respond to user- initiated events quite easily. Some effects that are now possible with JavaScript were some time ago only possible with CGI. So you can create really sophisitcated pages with the help of JavaScript. You can see many examples for JavaScript scripts on the Internet. Best you have a look at some JavaScript enhanced pages. You can find many links at Gamelan => http://www.gamelan.com (in the JavaScript section).

Overview over the different parts

Overview over the different parts

Part 1

What is JavaScript?

Running JavaScript scripts

Embedding scripts into HTML

A first function

Form elements

Last changed - date

Part 2

Information in the statusbar

Date object

Creating random numbers

Working with windows

Part 3

Working with frames

Part 4

The statusbar

The setTimeout function

Programming a scroller

Part 5

Arrays

How to clear a document

Back and Forward- buttons

Part 6

Load two frames with one click

Opening a new window when a link is taken

Operators

Part 7

Validating forms

Submitting form input

How to set the focus to a certain element

Introduction To Java Script

Introduction To Java Script

This is an introduction to JavaScript. JavaScript is a rather new scripting language for the Internet. I hope that you get to learn JavaScript fast with this tutorial. You will see soon that it is really easy to understand. The printable version is meant to be easier to read - and it can be better used as a reference. Of course you cannot try the examples immediately like in the online version. So you better check out the online version as well. As this language is being developed all the time there can be major changes. So please be sure to check back on my site to see if there are further parts. You can find this tutorial at http://rummelplatz.uni-mannheim.de/~skoch/js/script.htm. My e-mail address is skoch@rummelplatz.uni-mannheim.de.