Javascript: an introduction — the DOM
Writing your first script
Pages:
Javascript is a powerful scripting language that:
- can make a page more dynamic,
- can react to events,
- can validate form data prior to submission,
- can detect browser details,
- can create cookies.
The script is embedded in an html page either directly or as a separate file referenced by the web-page. As a scripting language it's very powerful and it has all of the functionality of any programming language.
You can write Javascript within the body of an html page or in the head and it will be executed as the page is loading. Or, and much more powerful overall, you can write Javascript functions in the head, which will only be executed when they're called.
However, wherever you write your Javascript, it must be enclosed within the following start/end tag pairs:
<script type="text/javascript"> // all javascript goes here </script>
Occasionally you can get errors in your xhtml validation when using javascript in which case you can add this to stop such errors, I won't bother explaining why:
<script type="text/javascript"> //<![CDATA[ // all javascript goes here //]]> </script>
Before you can start to write some javascript you need to know a few things — this is assuming you already know a bit about programming — you need to know how to declare a memory variable, how to do an IF statement (a selection) and a WHILE or FOR (an interation). You'll need to know how to move through arrays, and write and call functions. Oh, and a little bit about events too, since javascript is great at responding to events, in other words what happens when the user clicks the mouse, or moves it, or selects something, or deselects it, or loads the page.
You already know these things in some other programming language so you should find it straightforward to transfer to javascript. If you've never programmed before, well, I still don't think it's that difficult.
It'd be fastest if we could just plug into the computer and get a sub-vocal mind-tap, just download from me directly, but perhaps the next quickest way is this. I'm going to give you a few code snippets that do various things and I'll try and explain what they do. Then I'm going to give you a task to do that will need you to re-cycle the bits I've given you.
Variables, Selections, & Iterations
The image on the right shows some code that would count up to 10 and display each number on the page and if the number is 5 it displays it in bold. Since it's going to write wherever it's placed on the page it must go in the body section. Notice how I initialise a variable, do an iteration, write to the page and do an IF statement. Notice also how I finish each line and how I write a comment. Here's a simple version with no IF statement for making things bold.
By the way, if you mouseover the image you'll see the For Loop version.
Now here's the version including the bold part, together with comments which explain bits of the code, and once again, mouseover the image to see the For loop version:
Summary
- Variables
- To declare a variable you simply put
var NameOfVariable;
. If you want you can give the variable a value at the same time:var NameOfVariable = value;
. - Selections
- To write an IF statement you write:
An expression can be anything that evaluates to either true or false, like
if ( expression ) { actions if expression is true; } for example: if ( number == 5 ) { alert( "number is 5" ); }
number <= 10
, ornumber == 5
- Notice that to assign a value to a variable you used a single equals sign, the assignment operator. However, to test whether a
variable equals something, the equality operator, you use double equals. To emphasis the point:
number = 5; // makes the variable number equal 5 number == 5; // tests whether number does equal five (evaluates to true if it does);
- Iterations
- There are a number of different ways to do iterations or loops in javascript, the same as in any other programming language. Some are good for looping while a condition is true
others for looping and doing a count at the same time, some are good for looping through a collection or array of things.
Here's an example of the first of those, looping for as long as, or while, something is true:
while ( expression ) { actions if expression is true } for example: while ( number <= 10 ) { document.write( number + ", " ); }
- Writing Output
- To write output directly to the web page you can use a method of document object. We'll find out about the different objects
that make up a web page later, at the moment just accept that document is one of them. Anyway, to write output you write:
document.write( whatever_you_want );
- Script tags
- One last thing, remember when writing javascript you can write it in the head or body section of a web page but it must
be in between these tags:
<script type="text/javascript"> //<![CDATA[ // all javascript goes here //]]> </script> for example: <script type="text/javascript"> //<![CDATA[ while ( number <= 10 ) { document.write( number + ", " ); } //]]> </script>
Task One
You will need to create some web pages, one for each of these tasks, please create them in U:\local-html\jsIntro (you might need to create those two
directories). Name each file task1_1.html, task1_2.html, task1_3.html etc.
Here is a link to a
blank xhtml file
from which you can cut and paste the code into your editor to get you started.
- Count down. Quickly write some javascript in a web page that counts down from 10 to 1 and make it write the number 7 in italic and also make it say "All finished" at the end of the count.
- Inches to centimetres converter. Use 2.44 cm = 1 inch and use a prompt to ask for the number to convert, like this:
<script type="text/javascript"> //<![CDATA[ var inches = prompt("please enter a number of inches to convert to centimetres "); // then do your calculation with the variable inches // and display the answer in some friendly form. //]]> </script>
- 'Times Table' page. Ask the user, by using a javascript
prompt
, for any number between 1 and 12 and then produce a times table web page for that number. Try an incorporate some checking that the number is between 1 and 12.
Resources
Here are some resources that might help in completing the tasks and in extending your knowledge of Javascript. Of course a search with your favourite search engine will give you lots more too.
- Firebug Video, a short video tutorial introducing the Firebug add-in for Firefox. Firebug is a debugger for javascript, an html, css and DOM inspector - and it's great.
- Javascript Language Reference is the essential reference work, though I don't know if they have a slow server for this because I often get timeouts when accessing this site.
- w3schools.com have a good tutorial that starts with the basics that you might find helpful.
Pages: