Introduction
Thousands of sites around the world use JavaScript but it is still not a particularly well known programming language (compared to HTML). If you have seen anything interactive on a website like a calculation, pop-up-window, some web counters and even some navigation systems then you have probably seen JavaScript.
Unfortunately, JavaScript has changed from being a language which improves web sites to a language which destroys them. This is because there are huge JavaScript sites which have thousands of scripts for download. These usually involve things which do not benefit a website at all, like status bar effects and scrolling text which do not add much to a website.
JavaScript must not be confused with Java. Java is a completely different programming language. It is usually used for text effects and games, although there are some JavaScript games around.
So why should you use JavaScript? Well, JavaScript can allow you to create new things on your website that are both dynamic and interactive, allowing you to do things like find out some information about a user (like monitor resolution and browser), check that forms have been filled in correctly, rotate images, make random text, do calculations and many other things.
In this tutorial I am assuming that you understand HTML.
What Do I Need?
You will not need any special hardware or software to write JavaScript, you can just use Notepad or any other text editor. You do not even need to have any special software on your webserver. JavaScript will run on any webserver anywhere! All you will need to do is make sure that you have at least a version 3 browser, as versions of Internet Explorer and Netscape Navigator before this do not support JavaScript, so you will not be able to see your creations.
Declaring JavaScript
Adding JavaScript to a web page is actually surprisingly easy! To add a JavaScript all you need to add is the following (either between the <head></head> tags or between the <body></body> tags - I will explain more about this later):
Code: Select all
<script language="JavaScript">
JavaScript
</script>
There are two things you must do to hide the code from older browsers and show something instead:
Code: Select all
<script language="JavaScript">
<!--Begin Hide
JavaScript
// End Hide-->
</script>
<noscript>
HTML Code
</noscript>
Because of this the <noscript> tag was created. This will be ignored by browsers which understand <script> but will be read by the older browsers. All you need to do is put between <noscript> and </noscript> what you want to appear if the browser does not support JavaScript. This could be an alternative feature or just a message saying it is not available. You do not have to include the tag if you don't want anything shown instead.
Commenting
Something you might have noticed in the example above was that on the line:
Code: Select all
// End Hide-->
There was a:
//
It is very important in JavaScript, as with any other programming language to include comments, especially if you want others to learn from your code. It is also useful for including a copyright message.
Part 2 - Alerts, Prompts & Variables
Introduction
In part 1 I showed you how to declare a JavaScript and make sure that non-compatible browsers can see something. In this part I will show you how to actually do something with your JavaScript.
Alerts
The first JavaScript command I will show you is:
Code: Select all
alert()
Code: Select all
alert('Text for alert box');
Here is the full JavaScript for the earlier example:
Code: Select all
<script>
<!-- Start Hide
// Display the alert box
alert('This text is in an alert box');
// End Hide-->
</script>
Variables
Variables in JavaScript, as in other computer languages, can be used to store information. For example I could tell the computer that the variable called:
my_number
should have the value:
3456
Variables can also contain text for example the variable:
my_name
could have the value:
Neo Cambell
Variables can be very useful for text or numbers that you repeat several times in a program, for doing calculations or for getting input from a user. Variables are declared as follows:
Number:
Code: Select all
var my_number = 3456;
Code: Select all
var my_name = 'David Gowans';
When naming your strings you can use any word or combination of words as long as it is not already in use by JavaScript (so don't use alert as a variable name etc.). Do not include spaces, replace them with _.
Calculations
You can do calculations if you have variables containing numbers. Here is an example of some code which does a calculation:
Code: Select all
// Set Variables
var first_number = 15;
var second_number = 5;
var third_number = 10;
var fourth_number = 25;
//Do Calculations
var new_number = first_number + second number
var answer = new_number * third_number
var answer = answer / fourth_number
Getting Information From The User
Once you have started using variables you will realize that it will be quite useful to get some information from the user. You can do this by using the following command.
Code: Select all
prompt()
First of all, the new prompt command is used. I set the variable your_n
ame using it:
Code: Select all
var your_name = prompt('Please enter your name', 'Your Name');
After this I have to create the output string. I do this by adding together the input with two strings I declared earlier. (Refer to the file)
Code: Select all
var output_text = welcome_text + your_name + closing_text;
Finally I displayed the output_text variable in an alert box with the following code:
Code: Select all
alert(output_text);
Part 3 - Displaying Information
Introduction
In the last part I showed you how to display alert boxes and how to get information from the user. I also explained how variables work.
Code: Select all
document.writeln
Code: Select all
document.writeln('Hello there!');
Code: Select all
document.writeln('<font face="Arial" size="5" color="red">Hello there!</font>');
Hello there!
As you can see, this allows you to just put standard HTML code into a web page using JavaScript. If you can't see a good reason for this it is not surprising at the moment but next I will introduce variables to the script.
Outputting Variables
If you look at the final example I did in the last part, where I took information from the user and added it to some other text before displaying the output in an alert box. This can also be displayed in the page. Before doing this, though, I will explain a little more about where you can put your JavaScript code.
Up until now all the JavaScrit code has been contained inside the <head> and </head> tags of the HTML document. The reason for this is that the JavaScript will be loaded and executed before the rest of the document. This works fine for most scripts but, as the scripts become more advanced, you may need to have them both in the document and the head. I will use this script to demonstrate.
To put JavaScript in the <body></body> section of the page is exactly the same as putting it in the <head></head> section of the page. I would suggest that you adopt the following way of creating scripts:
Put all your initialization code in the head of the page (like setting variables, prompts, alerts etc.) and then all display code (document.writeln etc.) in the body of the page. This is the code for the new improved version of the example which uses document.writeln:
Code: Select all
<html>
<head>
<title>Variable Example</title>
<script>
<!-- Start Hide
// Set Variables
var welcome_text = 'Hello there ';
var closing_text = '! How are you?';
// Display prompt
var your_name = prompt('Please enter your name', 'Your name');
// Create Output Variable
var output_text = welcome_text + your_name + closing_text;
// End Hide-->
</script>
</head>
<body>
<script>
<!-- Start Hide
// Display Text
document.writeln('<font face="Arial" size="4">' + output_text + '</font><Br><Br>');
// End Hide-->
</script>
<a href="index3.htm#variables"><font face="Arial">Back</font></a>
</body>
</html>
As you can see from the above code, variables are added into document.writeln by using the + signs. There are no quotes round the variable names.
Remote JavaScript
Now you have learnt how to use the document.writeln command you can now start using one of the most useful applications of JavaScript, remote scripting. This allows you to write a JavaScript in a file which can then be 'called' from any other page on the web.
This can be used for things on your own site which you may like to update site-wide (like a footer on the bottom of every page) or something used on remote sites (for e
xample newsfeed or some counters).
To insert a remote JavaScript you do the following:
Code: Select all
<script language="JavaScript" src="http://www.yourdomain.com/javascript.js">
</script>
If you want to include information for browsers which do not support JavaScript you will need to put the <noscript></noscript> tags in the HTML, not the JavaScript file.
There is one problem with using remote JavaScript which is that only the recent browsers support it. Some browsers which support JavaScript do not support Remote JavaScript. This makes it advisable not to use this for navigation bars and important parts of your site.
Part 4 - Browser Windows
Introduction
In the last part I showed you how you can use JavaScript to prompt the user for information and how you can display HTML via JavaScript. In this part I will show you how you can create and manipulate browser windows using JavaScript.
Windows and HTML
Before learning how to create and manipulate windows in JavaScript, it is important to know how to create and manipulate them in HTML. The HTML manipulation is very basic but will also help you to understand how windows work in web browsers.
Firstly you must know the two ways of creating a link which opens in a separate window. The most common use is to have:
Code: Select all
<a href="link.html" target="_blank">Click Here</a>
A less common way of opening a new window is to use:
Code: Select all
<a href="link.html" target="mywindow">Click Here</a>
Code: Select all
<a href="page2.html" target="mywindow">Change the page</a>
Knowing about how a window name works is very important as you must understand it to use JavaScript windows effectively.
Opening A Window With JavaScript
The first thing you should learn to do with JavaScript is to do exactly the same thing with JavaScript as you could do with HTML. The JavaScript command used to open a window is:
Code: Select all
window.open
Code: Select all
window.open('link.html','mywindow');
This code can either used as part of your JavaScript code (for example if you included it in the JavaScript code in the <head> section of your page it would open when the page loaded) or can be used when a link is clicked. To do this you must use another JavaScript command called onclick.
I will give you more information about how this command works in a later part but for now all you really need to know is the following: In your standard HTML code include a link as follows:
Code: Select all
<a href="#" onClick="window.open('link.html','mywindow');">Click Here</a>
Manipulating The Window
The main reason of using JavaScript to manipulate windows, though, is because you can set many things on the window which you could never do with HTML. JavaScript allows you to use commands to decide which parts of the browser window appear. This is done using a third part of the window.open command. This is where you decide the window features:
Code: Select all
window.open('link.html','mywindow','window features');
Code: Select all
window.open('link.html','mywindow','location, status');
Feature | Function |
menubar | The File, Edit etc. menus at the top of the browser will be shown |
scrollbar | This will show scrollbars at the side of the window if they are needed |
width | You can set the width of the window in pixels (see the next section) |
height | You can set the height of the window in pixels (see the next section) |
toolbar | This will display the browser toolbar with the Back, Stop, Refresh buttons etc. |
location | The location bar (where you type in URLs) will be displayed in the browser |
resizable | This will allow the window to be resized by the user |
directories | This will show the directories in Netscape browsers like 'Whats new' and 'Whats cool' |
You may be a little confused by all these options so I will show you a few examples of opening a window in JavaScript:
This window will open with a location bar, toolbar and will be resizable:
Code: Select all
window.open('window1.htm','the_first_window','location, toolbar, resizable');
Code: Select all
window.open('window2.htm','thefirstwindow');
This will open a window 200 pixels wide and 300 pixels high. It is not resizable and has a status bar and will scroll if necessary. This is a very commonly used combination:
Code: Select all
window.open('window1.htm','thesecondwindow','height=300,width=200,status,scrollbars');
Introduction
In this part I will show you how to use link events, do image swaps and display things in the browser status bar.
Link Events
A link event is a different way of including JavaScript on your page. Instead of having <script> tags in your HTML you can set JavaScript that will only be executed when certain things happen.
There are three ways of executing some JavaScript code in a link. They are:
onClick
onMouseOver
onMouseOut
They can have many different uses but the most common is for image swaps (mouseover images).
onClick
onClick works in exactly the same way as a standard HTML link. It is executed when someone clicks on a link in a page. It is inserted as follows:
Code: Select all
<a href="#" onClick="JavaScript Code">Click Here</a>
onMouseOver and onMouseOut
onMouseOver and onMouseOut work in exactly the same way as onClick except for one major difference with each.
onMouseOver, as the name suggests, will execut the code when the mouse passes over the link. The onMouseOver will execute a piece of code when the mouse moves away from the link. They are used in exactly the same way as onClick.
Rollover Images
This is one of the main ways of using link events. If you have not seen rollover images before, they are images (usually used on navigation bars like the one at the top of this page) and when the mouse moves over the link it changes the image which is displayed.
This is done using a combination of the onMouseOver and onMouseOut events. To explain - when the mouse passes over the link you want the image to change to the new image, when it moves away from the link, the old picture should be displayed again.
The first thing you must do is edit the <img> tag you use to insert the image you want to change. Instead of just having something like this:
Code: Select all
<img src="home.gif" alt="Home">
Code: Select all
<img src="home.gif" alt="Home" name="home_button">
Now you have given a name to the image you are using you will want to create the rollover. The first thing you must do is create the image for the rollover and save it. Then create a link round the image. If you don't want to have a link on the image you can still do a rollover by specifying the href as # which will make the link do nothing eg:
Code: Select all
<a href="#"></a>
Code: Select all
<a href="index.htm" onMouseOver="home_button.src='homeon.gif';" onMouseOut="home_button.src='home.gif';"><img src="home.gif" alt="Home" name="home_button" border="0"></a>
Firstly you are creating a standard link to index.htm. Then you are telling the browser that when the mouse moves over the link the image with the name home_button will change to homeon.gif. Then you are telling it that when the mouse moves away from the link to change the image called home_button to home.gif. Finally you are inserting an image called home_button with an alt tag of 'Home' and no border round it.
If you have read the last part of the tutorial you will see t
hat onClick, onMouseOver and onMouseOut can be used with text links as well as images in exactly the same way as you did above. This, of course, means that you can create interesting effects by, when the mouse moves over an image, another image changes. This could be very useful for placing a description of a link on a page.
Status Bar
The status bar is the grey bar along the bottom of a web browser where information like, how much the page has loaded and the URL which a link is pointing to appears. You can make your own text apppear in the status bar using the JavaScript you already know using the following code:
Code: Select all
window.status='Your Text In Here';
Part 6 - If and Loops
Introduction
In previous parts I have shown you how to declare a JavaScript, open windows and display information. In this part I will show you how to use two of JavaScripts most important functions, If and Loops.
If
The if function allows you to check to see if something is true or false. For example you could check to see if text entered by a user matches a piece of text you already have (like a password). To show if in action click here.
As you can see this could be very useful for many sites. The code is as follows:
Code: Select all
var guess = prompt("Please guess a number between 1 and 10","");
if(guess == 5)
{
alert('Correct! I was thinking of 5');
}
else
{
alert('Wrong! I was thinking of 5');
}
Code: Select all
if(guess ==5)
Code: Select all
{
alert('Correct! I was thinking of 5');
}
Code: Select all
else
{
alert('Wrong! I was thinking of 5');
}
Together this code makes up the if statement.
More If
There are other conditions you can test with the if statement. Firstly, as well as using numbers you can compare variables or text:
Code: Select all
if(variable == variable)
if(variable == "some text")
Code: Select all
if(variable < othervariable)
Code: Select all
if(variable > othervariable)
Code: Select all
if(variable <= othervariable)
Code: Select all
if(variable >= othervariable)
Code: Select all
if(variable != othervariable)
These can be very useful in your web pages. You can also check to see if two conditions are true before executing code using &&:
Code: Select all
if(variable1 == variable2) && (variable1 < variable3)
Code: Select all
if(variable1 == variable2) || (variable1 < variable3)
While Loops
While loops are pieces of code which will repeat until the condition is met. This is very useful for things like passwords when you want to keep asking the user until they get it correct. For example this code will repeat until the user enters the word 'hello':
Code: Select all
var password = 'hello';
var input = prompt('Please enter the password', '');
while(input != password)
{
var input= prompt('Please enter the password''');
}
For Loops
For loops are used to do something a set number of times. For example:
Code: Select all
for(loop=0; loop < 11; loop++)
{
document.writeln(loop);
}
Code: Select all
for(starting value; test; increment)
Part 7 - Forms & Functions
Introduction
In part 6 I showed you how to use If and loops. In this part I will show you how you can manipulate HTML forms with JavaScript to improve your website.
Changing The Value Of A Text Box
Before you can manipulate text boxes you must first know how to create a form and how to create a text box in HTML. I will quickly explain this.
Forms for JavaScript are slightly different to standard ones as they do not require any information or script to handle them. You can do everything by just giving the form a name (although later you may want to add the other information so that you can also have the form submitted):
Code: Select all
<form name="formname">
</form>
Code: Select all
<input type="text" name="boxname">
Code: Select all
window.document.example1.first_text.value='Hi there';
You can also do this with multiline text boxes. You can use
Code: Select all
/n
In this section, you have learnt the most important part of this lesson, how to refer to an item in a form.
Events
Just like links, you can set events for items in a form. They are:
onBlur - Happens when the cursor is moved out of the field
onFocus - Happens when the cursor is moved into the field
onChange - Happens when the field is changed and the cursor moves out of it
These are placed into the code as part of the form's item for example:
Code: Select all
<input type="text" onBlur="dothis">
JavaScript functions are very useful, and this seems an appropriate place to introduce them. They are pieces of JavaScript which can be declared at the top of your page and can then be referred to again and again in your code. You can even pass parameters to them and make them do different things.
Functions take the following form:
Code: Select all
function functionname(parameters)
{
}
Code: Select all
function sayhello()
{
alert(Hello there!);
}
Code: Select all
<a href="#" onMouseOver="sayhi();">Say Hello</a>
Parameters
Parameters are a very useful part of functions. They allow you to pass data to the function when it is called. Here is an example:
Code: Select all
function say(what)
{
alert(what);
}
Code: Select all
<a href="#" onMouseOver="say(hello);">Say Hello</a>
<a href="#" onMouseOver="say(goodbye);">Say Good Bye</a>
As you can see functions and parameters are very useful.
Part 8 - More Forms
Introduction
In the last part I explained a few of the things you can do using forms. In this, the final part, of the JavaScript tutorial I will explain how you can do some other things with your JavaScript forms.
Using The Submit Button
The most common use of forms is to submit data to a script so that it can be processed. This is fine if you are using CGI to do a mailto form or something like that, but if you just want to run a piece of JavaScript from a form you will need to do things a little differently. The first part you must learn about is the return false; attribute. It can be used as follows:
Code: Select all
<form name="myform" onSubmit="return false;">
<input type="submit" value="Submit">
</form>
Code: Select all
<form name="myform" onSubmit="MyFunction(); return false;">
Code: Select all
return false;
Checkboxes
Checkboxes and radio buttons are two of the remaining form items. First I will cover checkboxes.
Checkboxes have two possible values:
As there are only two possible values, the JavaScript to refer to a checkbox is slightly different to that of a text box. In the example below the checkbox has been given the name my_checkbox and is in the form example1.
Code: Select all
if(window.document.example1.my_checkbox.checked=true)
{
alert('The box is checked!')
}
else
{
window.document.example1.my_checkbox.checked=true;
alert('The box was not checked so I have checked it!');
}
If, of course, you want to check or refer to the unchecked value of a checkbox the code would be:
Code: Select all
window.document.example1.my_checkbox.checked=false;
As with all other form objects you can use onBlur, onChange and onFocus.
Radio Buttons
Radio buttons are usually found in groups like this:
Only one button in the group can be checked at a time. Radio buttons work in exactly the same way as a checkbox, having a .checked property which can either be true or false.
Selects and Menus
The two remaining form elements are selects and menus. I will cover menus first. Menus are drop down boxes with several options in them (they are mainly used for things like selecting your country on a form). Selects are really just menus with multiple lines and scrollbars. To show how they work I will show you a quick example of a menu in action and the code for it. For a select box I would just change the height propery. To see the example click here. The code used is below:
Code: Select all
<form name="go" onSubmit="return false;">
<select name="select" onChange="window.document.location=window.document.go.select.value;">
<option value="#" selected>Please Select</option>
<option value="http://www.coderlink.com">CoderLink</option>
<option value="http://www.buytiptop.com">BuyTipTop</option>
<option value="https://robot.lk">ROBOT.LK</option>
</select>
</form>
Code: Select all
window.document.location
Conclusion
In this tutorial I covered some of the most important parts of JavaScript and now you should be able to start writing some quite advanced scripts. There is still a lot of JavaScript left to learn with many more advanced commands. In the future I will do a tutorial on this. One way of improving your skills, though, is to look at the code of other people's pages that use JavaScript. Don't steal them but you can learn more about the language by doing this.