JAVASCRIPT 101 Course
Do you have Javascript difficult?
JAVASCRIPT 101 Course
You do not need prior programming experience to be able to follow this tutorial series that takes you step by step through how to write your own Javascript programs. No longer will you have to rely on pre-built scripts written by others. You will be able to write your own scripts that do exactly what you want them to do.
Getting Started
Introduction
Learning a programming language is a daunting task for anyone who hasn't learnt one before. One of the biggest problems is trying to do too much too soon. If you don't have a firm grasp of the basics then you will soon be floundering out of your depth and wonder why you thought to try programming in the first place.
Taking things slowly means that you will not be producing the really fancy scripts that you want for quite some time. Of course even the most simple piece of Javascript code can be useful.
Another thing that confuses many beginners is that programmers use what is almost a foreign language when talking about programming. Terms such as "variable", "function", "object" and so forth don't have just their regular English meanings but also sometimes different and quite specific meaning to programmers. It is impossible to avoid using such terms in introducing you to programming as the terminology is something that you need to know in order to look up further information in various books and references. Don't worry though because whenever I start using "computer speak" I will also explain in plainer English what the terminology means as well as giving examples so you can see for yourself exactly what it means. You'll also find the terms in the Glossary so that you can look up the meaning there if you missed the earlier description.
In the tutorials that follow, no previous programming knowledge is needed. The tutorials will introduce you step by step to both programming and the Javascript programming language. We will start with programming basics and gradually build on this in small steps to cover what you need to know to be able to create your own Javascripts from scratch that will do what you want them to do.
What the Classical Course Includes
The following is a list of the topics that are covered in this tutorial series. Note that the material in this course covers much of the same material as the modern course does but covers the way that people used to handle the tasks using javaScript. While much of the code that is used for modern coding is the same as the classical method (which is why I haven't removed these tutorials) some of the material presented in these tutorials is more appropriate for antiquated browsers such as IE4 and Netscape 4 rather than modern browsers such as Firefox 3, Opera 9.5, Safari 3 and IE8.
1. Hello World
2. Variables
3. Operators
4. The IF Statement
5. The CASE Statement
6. Functions
7. Variable Scope
8. Passing Parameters
9. Values of Functions
10. ALERT and CONFIRM
11. Comments
12. Finding and Fixing Errors
13. External Javascripts
14. Using NOSCRIPT
15. Objects and Properties
16. Arrays
17. FOR Loops
18. WHILE Loops
19. Date and Time
20. Mathematical Functions
21. String Processing
22. Document Object Model
23. The Internet Explorer DOM
24. The Netscape DOM
25. The W3C DOM
26. Cross Browser DOM
27. Event Handlers
28. Mouse Events
29. Keyboard Events
30. Form Handling Events
31. Page Load/Unload Events
32. Timed Events
33. Global Events
34. Object Oriented Javascript
35. Defining Classes
36. Putting it all Together
Getting Started
Introduction
Learning a programming language is a daunting task for anyone who hasn't learnt one before. One of the biggest problems is trying to do too much too soon. If you don't have a firm grasp of the basics then you will soon be floundering out of your depth and wonder why you thought to try programming in the first place.
Taking things slowly means that you will not be producing the really fancy scripts that you want for quite some time. Of course even the most simple piece of Javascript code can be useful.
Another thing that confuses many beginners is that programmers use what is almost a foreign language when talking about programming. Terms such as "variable", "function", "object" and so forth don't have just their regular English meanings but also sometimes different and quite specific meaning to programmers. It is impossible to avoid using such terms in introducing you to programming as the terminology is something that you need to know in order to look up further information in various books and references. Don't worry though because whenever I start using "computer speak" I will also explain in plainer English what the terminology means as well as giving examples so you can see for yourself exactly what it means. You'll also find the terms in the Glossary so that you can look up the meaning there if you missed the earlier description.
In the tutorials that follow, no previous programming knowledge is needed. The tutorials will introduce you step by step to both programming and the Javascript programming language. We will start with programming basics and gradually build on this in small steps to cover what you need to know to be able to create your own Javascripts from scratch that will do what you want them to do.
What the Classical Course Includes
The following is a list of the topics that are covered in this tutorial series. Note that the material in this course covers much of the same material as the modern course does but covers the way that people used to handle the tasks using javaScript. While much of the code that is used for modern coding is the same as the classical method (which is why I haven't removed these tutorials) some of the material presented in these tutorials is more appropriate for antiquated browsers such as IE4 and Netscape 4 rather than modern browsers such as Firefox 3, Opera 9.5, Safari 3 and IE8.
1. Hello World
2. Variables
3. Operators
4. The IF Statement
5. The CASE Statement
6. Functions
7. Variable Scope
8. Passing Parameters
9. Values of Functions
10. ALERT and CONFIRM
11. Comments
12. Finding and Fixing Errors
13. External Javascripts
14. Using NOSCRIPT
15. Objects and Properties
16. Arrays
17. FOR Loops
18. WHILE Loops
19. Date and Time
20. Mathematical Functions
21. String Processing
22. Document Object Model
23. The Internet Explorer DOM
24. The Netscape DOM
25. The W3C DOM
26. Cross Browser DOM
27. Event Handlers
28. Mouse Events
29. Keyboard Events
30. Form Handling Events
31. Page Load/Unload Events
32. Timed Events
33. Global Events
34. Object Oriented Javascript
35. Defining Classes
36. Putting it all Together
Hello World
Introduction
Just about all programming courses start off with a simple program called "Hello World". This program is designed to output the text "Hello World" from the program and is designed to introduce you to the programming language and show you how to write, compile, and execute programs using that language. JavaScript is a scripting language so it doesn't need to be compiled - instead it is executed directly by the web browser - but we still need to know how to write the code and attach it to our web page.
Your First Script
The first thing that we need to do is to add some HTML into the body section of our web page.
<script type="text/javascript">
</script>
These two lines form a container into which we can place our JavaScript code. The parameters on the script tag identify the content surrounded by these tags as JavaScript code to be executed rather than text to be displayed.
There will also be times when you will want to add JavaScript to the head section of your page (which is the best place to put it all) and some JavaScript can even be added into parameters in the HTML tags themselves but for the first few tutorials we will stick with placing our JavaScript between these tags in the body section of the page.
Where about's in the body section should you place the tags? Well the JavaScript is going into the body section of your page because we intend to use the JavaScript to display something on the page. The script tags (and the JavaScript that we are about to add to it) should therefore be positioned within your page content at the place where we want the output from the script to appear.
The usual purpose of a "Hello World" script is to output the text "Hello World" so let's add the JavaScript statement to do this between the HTML script tags. The complete code added to the page will now look like this:
<script type="text/javascript">
document.write('<b>Hello World</b>');
</script>
So let's examine our first line of JavaScript and see what we have learned so far about writing JavaScript code.
The first thing that we have learned is that we can get JavaScript to output something to our web page by using document.write. The "document" part of this command identifies the current web page as what we are updating and the "write" is how we are updating it - ie. by writing something to the page. You will find the what portion of these commands is usually referred to as an object and the how portion is usually referred to as the method. The actual value that is to be written out is contained between the parentheses that follow.
In this instance we want to write out the text "Hello World". In the example I have surrounded the text with apostrophes (') rather than quotes ("). Surrounding your JavaScript text with apostrophes rather than quotes will make it easier to including quotes in the text to be written out.
The example text is also surrounded by HTML bold tags. This will result in the text being displayed on the page in bold. You can easily include HTML code into your JavaScript document.write statements and since the JavaScript writes its output into the page before the page is processed by the browser, any HTML that is included will be processed exactly the same as if it were statically coded into the page.
Finally you will notice that the line ends with a semi-colon (. The semi-colon is what determines where individual JavaScript statements end in the same way that a greater than (>) determines where an HTML tag ends.
The document.write statement is the easiest way to output something into our web page. It certainly isn't the best way (it's the worst way) but it is the easiest way and so we will use it through the earlier tutorials while looking at the core part of the JavaScript language.
If you look at other people's JavaScript you may find a language="javascript" (possibly with a number on the end). That part of the script tag is now obsolete and should be removed (you may still find it on some of the pages of this site that were written some time ago and which I haven't yet had time to go back and correct, if you do then just make sure you use type='text/javascript' instead).
Using What You Know
At this stage you are probably wondering what you can possibly do using just the JavaScript that you have learned in this first tutorial. Well not everyone uses a web browser that supports JavaScript and some whose browsers do support JavaScript have it disabled. We can make use of what we already know to hide parts of our page from those whose browsers don't support JavaScript.
Suppose that we have obtained some complex JavaScript from one of the many JavaScript libraries available on the internet and have followed the instructions to install it on one of our web pages. We might now have a web page that only functions correctly when JavaScript is enabled. It would be preferable if we could hide the existance of that page from visitors whose browsers don't have JavaScript enabled.
We can use what we have learned in this tutorial to edit the page(s) that link to the page that we want to hide so that the link only appears when JavaScript is enabled. To do this we locate the HTML code in the page that forms the link to the page to be hidden and replace the static link code with our JavaScript code above. For example, suppose the static link code reads as follows:
<a href="script.htm">Page Requiring JavaScript</a>
We would replace this code exactly where it appears with:
<script type="text/javascript">
document.write('<a href="script.htm">Page Requiring JavaScript</a>');
</script>
For visitors who have JavaScript enabled the page will look exactly the same as before but for those visitors without JavaScript the link to script.htm no longer appears.
Just about all programming courses start off with a simple program called "Hello World". This program is designed to output the text "Hello World" from the program and is designed to introduce you to the programming language and show you how to write, compile, and execute programs using that language. JavaScript is a scripting language so it doesn't need to be compiled - instead it is executed directly by the web browser - but we still need to know how to write the code and attach it to our web page.
Your First Script
The first thing that we need to do is to add some HTML into the body section of our web page.
<script type="text/javascript">
</script>
These two lines form a container into which we can place our JavaScript code. The parameters on the script tag identify the content surrounded by these tags as JavaScript code to be executed rather than text to be displayed.
There will also be times when you will want to add JavaScript to the head section of your page (which is the best place to put it all) and some JavaScript can even be added into parameters in the HTML tags themselves but for the first few tutorials we will stick with placing our JavaScript between these tags in the body section of the page.
Where about's in the body section should you place the tags? Well the JavaScript is going into the body section of your page because we intend to use the JavaScript to display something on the page. The script tags (and the JavaScript that we are about to add to it) should therefore be positioned within your page content at the place where we want the output from the script to appear.
The usual purpose of a "Hello World" script is to output the text "Hello World" so let's add the JavaScript statement to do this between the HTML script tags. The complete code added to the page will now look like this:
<script type="text/javascript">
document.write('<b>Hello World</b>');
</script>
So let's examine our first line of JavaScript and see what we have learned so far about writing JavaScript code.
The first thing that we have learned is that we can get JavaScript to output something to our web page by using document.write. The "document" part of this command identifies the current web page as what we are updating and the "write" is how we are updating it - ie. by writing something to the page. You will find the what portion of these commands is usually referred to as an object and the how portion is usually referred to as the method. The actual value that is to be written out is contained between the parentheses that follow.
In this instance we want to write out the text "Hello World". In the example I have surrounded the text with apostrophes (') rather than quotes ("). Surrounding your JavaScript text with apostrophes rather than quotes will make it easier to including quotes in the text to be written out.
The example text is also surrounded by HTML bold tags. This will result in the text being displayed on the page in bold. You can easily include HTML code into your JavaScript document.write statements and since the JavaScript writes its output into the page before the page is processed by the browser, any HTML that is included will be processed exactly the same as if it were statically coded into the page.
Finally you will notice that the line ends with a semi-colon (. The semi-colon is what determines where individual JavaScript statements end in the same way that a greater than (>) determines where an HTML tag ends.
The document.write statement is the easiest way to output something into our web page. It certainly isn't the best way (it's the worst way) but it is the easiest way and so we will use it through the earlier tutorials while looking at the core part of the JavaScript language.
If you look at other people's JavaScript you may find a language="javascript" (possibly with a number on the end). That part of the script tag is now obsolete and should be removed (you may still find it on some of the pages of this site that were written some time ago and which I haven't yet had time to go back and correct, if you do then just make sure you use type='text/javascript' instead).
Using What You Know
At this stage you are probably wondering what you can possibly do using just the JavaScript that you have learned in this first tutorial. Well not everyone uses a web browser that supports JavaScript and some whose browsers do support JavaScript have it disabled. We can make use of what we already know to hide parts of our page from those whose browsers don't support JavaScript.
Suppose that we have obtained some complex JavaScript from one of the many JavaScript libraries available on the internet and have followed the instructions to install it on one of our web pages. We might now have a web page that only functions correctly when JavaScript is enabled. It would be preferable if we could hide the existance of that page from visitors whose browsers don't have JavaScript enabled.
We can use what we have learned in this tutorial to edit the page(s) that link to the page that we want to hide so that the link only appears when JavaScript is enabled. To do this we locate the HTML code in the page that forms the link to the page to be hidden and replace the static link code with our JavaScript code above. For example, suppose the static link code reads as follows:
<a href="script.htm">Page Requiring JavaScript</a>
We would replace this code exactly where it appears with:
<script type="text/javascript">
document.write('<a href="script.htm">Page Requiring JavaScript</a>');
</script>
For visitors who have JavaScript enabled the page will look exactly the same as before but for those visitors without JavaScript the link to script.htm no longer appears.
Defining Variables
Introduction
In this tutorial we will build on what we learned with our first script by creating a variable and displaying the value of that on our web page instead of displaying static text.
I'll start by explaining what a variable is. A variable is a named location in memory that is used to hold a value that can be modified by the program. If that doesn't make sense yet then it should by the end of this tutorial.
The Script
In our first example we coded the text that we wanted to display on the page directly into the write statement. Instead of coding the text directly into the document.write statement we will now create a variable containing that text instead.
<script type="text/javascript">
var hello = 'Hello World';
document.write(hello);
</script>
With this version of the script we no longer have the text to be displayed contained within the document.write statement. Instead we first define a variable called hello which we assign the value "Hello World" to and then we write out the content of the variable instead of static text.
This doesn't produce any different result on the page but the differences in the code introduce you to a number of new features of Javascript. This will also allow us to insert further statements into this Javascript code at a later date that will change the value of the variable before it is displayed on the page.
The first line in this script creates our first variable. To create a variable you specify var (for variable) followed by the name that we want to use for the variable. If we want to give the variable a value straight away then we follow the name with equals (=) and then the value that we want to use. We call this initializing the variable.
It is possible to define a new variable without preceding the variable name with var. Specifying a new variable name without the var in front will still result in a variable with the specified name being created (if one doesn't already exist). I recommend however that you always use var when you intend to define a new variable. In a later tutorial I will show you how you can create two variables with the same name but different scope (this means that only one is accessible at a time and where you are in the code determines which one you are referencing). If you leave off var when defining new variables you run the risk of using an existing variable instead of defining a new one. Always specifying var when defining new variables will also reduce the possibility that the variables you use in multiple scripts on the same page will interfere with one another.
Types of Variables
Javascript supports three types of simple variables. These are text, numbers, and boolean (true or false). In this case this variable is a text variable because the value we have initialized it with is text (because it is enclosed within apostrophes). Had we wanted to define the variable as a number then we would have given it a numeric value (not enclosed in apostrophes) like this:
var mynum = 5;
We could also have defined the variable as boolean by assigning it an initial value of true or false. For example:
var smokes = false;
If you don't assign a value to the variable straight away then the type of variable that it is will be undefined until you give it a value.
You can leave a variable undefined when you don't want to assign it an initial value but a better alternative where you don't want to give the variable a value straight away is to specify that the variable doesn't have a value at all. We do this by initializing the variable with null like this:
var riches = null;
Javascript also allows you to define and use more complex data types that are defined using classes. We'll go into more detail about classes in a later tutorial but here's an example of a variable defined from a class so that you know what they look like:
var today = new Date;
Naming Variables
So what should you call your variables? The best option (at least to start with) is to use meaningful names for all of your variables. If you call your variable openingPrice then you are far more likely to remember what the field is used for when you need to modify the script at a later date than if you call it op. The only restriction on what names you can use for your variables is that you can't use reserved words and all of the characters you use in the variable names must be alphanumeric. Reserved words are words that currently (or are expected in the future) to have a special meaning in the Javascript programming language. Examples of reserved words that you have already met include "var", "true", "false", "new", and "null". You'll find a complete list of reserved words elsewhere on this site.
Note that variable names cannot contain spaces. This means that when you use multiple words in a variable name that you must either separate the words with an underscore character (the only non alphabetic and non number character that nevertheless is considered to be alphanumeric) - for example: opening_balance - or you can do as I did in the previous paragraph and capitalize the first letter of the second and subsequent words. It doesn't matter which of these two options you choose but I suggest that you use that one consistently for your variable names rather than switching between them.
Using What You Know
Suppose that you have some web page content that appears in multiple places on the page. If you will need to update that repeating content then you will need to make sure that you make the changes at each spot in the page where the content appears. If you miss one when updating it then the content will no longer repeat correctly.
If we use a Javascript variable to store the content that is to be repeated then we can write that out to the several places on the page where the content is needed. If the content needs to be changed then you change it once in the declaration of the variable and all of the repetitions will reflect that change.
Suppose that the code to be repeated reads as follows:
<p>If you have any questions about this
please <a href="mailto:me@myaddress.com">email me</a>.</p>
This code might appear under each of say five separate sections of text on your page. If your email address were to change then you would need to update each spot on the page to the new email address. If you miss one then emails sent from that link will go to the wrong address.
So let's include that text into a Javascript variable instead. We will replace the first occurrence of the code with the following Javascript:
<script type="text/javascript">
var questions = '<p>If you have any questions about this
continued from previous line please <a href="mailto:me@myaddress.com">email me</a>.</p>';
document.write(questions);
</script>
Note: The line commencing with continued from previous line is a continuation of the previous line and I have split it into two lines to make it easier to read in browsers using lower screen resolutions. When you copy the script you should place the code on this line onto the end of the preceding line.
The other copies of the same code can be replaced with the following Javascript which will use the variable value previously assigned:
<script type="text/javascript">
document.write(questions);
</script>
In this tutorial we will build on what we learned with our first script by creating a variable and displaying the value of that on our web page instead of displaying static text.
I'll start by explaining what a variable is. A variable is a named location in memory that is used to hold a value that can be modified by the program. If that doesn't make sense yet then it should by the end of this tutorial.
The Script
In our first example we coded the text that we wanted to display on the page directly into the write statement. Instead of coding the text directly into the document.write statement we will now create a variable containing that text instead.
<script type="text/javascript">
var hello = 'Hello World';
document.write(hello);
</script>
With this version of the script we no longer have the text to be displayed contained within the document.write statement. Instead we first define a variable called hello which we assign the value "Hello World" to and then we write out the content of the variable instead of static text.
This doesn't produce any different result on the page but the differences in the code introduce you to a number of new features of Javascript. This will also allow us to insert further statements into this Javascript code at a later date that will change the value of the variable before it is displayed on the page.
The first line in this script creates our first variable. To create a variable you specify var (for variable) followed by the name that we want to use for the variable. If we want to give the variable a value straight away then we follow the name with equals (=) and then the value that we want to use. We call this initializing the variable.
It is possible to define a new variable without preceding the variable name with var. Specifying a new variable name without the var in front will still result in a variable with the specified name being created (if one doesn't already exist). I recommend however that you always use var when you intend to define a new variable. In a later tutorial I will show you how you can create two variables with the same name but different scope (this means that only one is accessible at a time and where you are in the code determines which one you are referencing). If you leave off var when defining new variables you run the risk of using an existing variable instead of defining a new one. Always specifying var when defining new variables will also reduce the possibility that the variables you use in multiple scripts on the same page will interfere with one another.
Types of Variables
Javascript supports three types of simple variables. These are text, numbers, and boolean (true or false). In this case this variable is a text variable because the value we have initialized it with is text (because it is enclosed within apostrophes). Had we wanted to define the variable as a number then we would have given it a numeric value (not enclosed in apostrophes) like this:
var mynum = 5;
We could also have defined the variable as boolean by assigning it an initial value of true or false. For example:
var smokes = false;
If you don't assign a value to the variable straight away then the type of variable that it is will be undefined until you give it a value.
You can leave a variable undefined when you don't want to assign it an initial value but a better alternative where you don't want to give the variable a value straight away is to specify that the variable doesn't have a value at all. We do this by initializing the variable with null like this:
var riches = null;
Javascript also allows you to define and use more complex data types that are defined using classes. We'll go into more detail about classes in a later tutorial but here's an example of a variable defined from a class so that you know what they look like:
var today = new Date;
Naming Variables
So what should you call your variables? The best option (at least to start with) is to use meaningful names for all of your variables. If you call your variable openingPrice then you are far more likely to remember what the field is used for when you need to modify the script at a later date than if you call it op. The only restriction on what names you can use for your variables is that you can't use reserved words and all of the characters you use in the variable names must be alphanumeric. Reserved words are words that currently (or are expected in the future) to have a special meaning in the Javascript programming language. Examples of reserved words that you have already met include "var", "true", "false", "new", and "null". You'll find a complete list of reserved words elsewhere on this site.
Note that variable names cannot contain spaces. This means that when you use multiple words in a variable name that you must either separate the words with an underscore character (the only non alphabetic and non number character that nevertheless is considered to be alphanumeric) - for example: opening_balance - or you can do as I did in the previous paragraph and capitalize the first letter of the second and subsequent words. It doesn't matter which of these two options you choose but I suggest that you use that one consistently for your variable names rather than switching between them.
Using What You Know
Suppose that you have some web page content that appears in multiple places on the page. If you will need to update that repeating content then you will need to make sure that you make the changes at each spot in the page where the content appears. If you miss one when updating it then the content will no longer repeat correctly.
If we use a Javascript variable to store the content that is to be repeated then we can write that out to the several places on the page where the content is needed. If the content needs to be changed then you change it once in the declaration of the variable and all of the repetitions will reflect that change.
Suppose that the code to be repeated reads as follows:
<p>If you have any questions about this
please <a href="mailto:me@myaddress.com">email me</a>.</p>
This code might appear under each of say five separate sections of text on your page. If your email address were to change then you would need to update each spot on the page to the new email address. If you miss one then emails sent from that link will go to the wrong address.
So let's include that text into a Javascript variable instead. We will replace the first occurrence of the code with the following Javascript:
<script type="text/javascript">
var questions = '<p>If you have any questions about this
continued from previous line please <a href="mailto:me@myaddress.com">email me</a>.</p>';
document.write(questions);
</script>
Note: The line commencing with continued from previous line is a continuation of the previous line and I have split it into two lines to make it easier to read in browsers using lower screen resolutions. When you copy the script you should place the code on this line onto the end of the preceding line.
The other copies of the same code can be replaced with the following Javascript which will use the variable value previously assigned:
<script type="text/javascript">
document.write(questions);
</script>
Permissions in this forum:
You cannot reply to topics in this forum