Css and Javascript
Css and Javascript
Css and Javascript
Introduction
CSS (Cascading Style Sheets) is a great new technology which is taking the web by
storm. The strange thing is, very few people have actually heard of it. You have probably
seen Stylesheets in action on many websites. Anywhere you see a text link change color
when you move your mouse over it probably uses stylesheets.
This is actually a very good question. Why should you learn a new web language just so
that links on your site change color? CSS actually has a lot more use than that. If you
want to change what an HTML tag does or be able to update a whole site by changing
one file, you will do that with CSS.
Cascading Style sheets let you do many things you could never do before. If you want to
change the <a> tag to always display text in bold, red, underlined you could do it with
Cascading Style sheets. If you later decided you wanted it green, font size 6 with no
underline you could change it just as easily. You can even link to a stylesheet file from
the pages on your site. When you update the stylesheet file you can see the updates in the
rest of your site.
Stylesheets also allow you to do things you never could with HTML. You can set
background colors for text, you can indent text using centimetre values and you can
place items exactly where you want them on a page. Most of this can be done from a
linked file and can be updated quickly.
For example, in HTML, if you want to set the first paragraph of every page to bold and
italics, you would have to do this for every single paragraph that needs it as in example
below:
<p>
<b><i>This is the first paragraph on page one. The same font styles are needed for each
page on my website</i></b>
</p>
With Stylesheets, you can get rid of all that code, and place it in the HEAD section of
your page. You would then just apply the Style to any paragraph that needs. For example,
the paragraph tage above can be given a CSS class and CSS rules is applied to that class.
Any other paragraph can then be given the same CSS class so that they share the same
properties E.g.
<p class = “paragraph-style”> This is the first paragraph on page one. The same font
styles are needed for each page on my website</p>
1
Then a CSS rule named “paragraph-style” will then be written inside an opening <style>
and a closing </syle> tag as follows:
<style>
.paragraph-style {font-size:24pt; font-weight: bold; font-style: italics;}
</style>
Note that the bold, italics and font size properties to any paragraph within the web page
which is assigned the “paragraph-style” CSS class. Also note that each property is
separated by semi-colon.
CSS Rules
A Cascading Stylesheet rule tells the browser what the HTML looks like, and what it
should do. A rule can dictate what just on HTML tag should look like, or you can
construct your own rule to be applied as and where you want it.
For example, a rule can be set up that tells the browser to format every <p> tag so that its
first line is indented. Or you could construct your own paragraph rule, and just apply the
style to certain paragraphs, not all paragraphs.
The Selector
There are three different kinds of CSS Selector: An HTML selector, a Class selector and
an ID selector.
An HTML Selector is the text part of an HTML tag. The complete paragraph tag is <P>.
So its Selector is just P. In other words, strip the angle brackets off and you get the
HTML selector.
A Class Selector is one you set up yourself, to be used anywhere on your page. The
“paragraph-style” in the example above is a Class Selector. You will pick the name of a
Class Selector yourself and then apply the style to some text on the page.
An ID Selector is similar to a Class Selector but you use them to identify a particular
element. It cannot be applied to other similar elements on the page except the element to
which it is assigned.
</style>
h1 {Color: Red}
2
.NewFont {Font-size: 16pt}
#NewTextboxColour {Color: yellow}
</style>
The first one, h1, is the HTML Selector. Notice that is has had its angle bracket removed.
With HTML selector, all the HTML tags on the page will be formatted in the style you
have set. So for h1 above, all the text between the <h1> and </h1> tags on the page will
now be in Red.
The second one, .NewFont, is the Class Selector. Note that a class selector must start
with a full stop (period). Then you type the name of the selector (any name you want).
No space is added between the full stop and the name of the selector.
The third one, #NewTextboxColour, is the ID selector. An ID selector starts with the
hash/pound (#) symbol. You then type the name you want to use for your ID selector.
Again, no space is added between the symbol and name of your selector.
Once you have set up your Selector, you then define the Properties and Values for that
selector. The Property for the selector is the thing you are trying to change. Examples are:
Font, Color, Background, Margin, Text, etc.
The Value for the selector is the new setting for the property. For example, for our
COLOR property, we can set it to a value of actual colour (red, blue, yellow) or a colour
code (#FFFF00, #000000).
The property and the value are enclosed in curly brackets { }. The syntax for the whole
thing would then be:
An example is:
h1 {Color: Red}
Note that the a property and its value are separated by a colon (:). If you have more than
one property and value, you must separate them by semi-colon (;). For example,
Each pair of properties and values can also be put on multiple lines separated by a semi-
colon like this:
3
<style>
h1
{
Color: Red;
Font-weight: Bold;
Font-size: 16pt;
}
</style>
There are 3 ways to include stylesheets on your page. You can have inline styles, which
let you change the style of one piece of text. The second way is to include or embed the
stylesheet information in the head of the document. This allows you to have a style
applied to the whole page without being the same as the rest of the site. Finally, you can
create a link to an external file in the head of your document. This is very useful if you
would like to make sitewide updates by changing one file.
You can place a style tag directly in a HTML tag. This is called inline. Inline styles will
override ones place elsewhere. For example,
<h1 style = “Color: Red; Font-weight: Bold; Font-size: 16pt”> My Heading is here </h1>
<html>
<head>
<title>CSS</title>
<style type="text/css">
Stylesheet in here
</style>
</head>
<body>
</body?
</html>
4
External Style Sheets
Instead of typing the <style> tags and the code for all your CSS rules in the HEAD
section, you can type it all in a separate text file. You then tell the browser where the text
file is. The text file (along with its code) is then treated as though it were in the HEAD
section.
To insert a linked stylesheet you need to put the following into the head of your
document:
To embed a stylesheet , the LINK tag is used. The REL attribute tells the browser that
you want to link to a stylesheet. The TYPE tells the browser what sort of file is being
used. The HREF attribute tells the browser the name of the file and where the file is.
External stylesheets have a big advantage over embedded ones because they can be used
for all pages in your website. All you need do is insert the LINK tag in the HEAD section
of your website pages. With Embedded stylesheets, you would have to include the same
style code in the HEAD section of every page.
External stylesheets are just text files which can be written in any text editor like
Notepad. No tags are used in the external stylesheets. There are no <STYLE> tags or
HTML tags, just the Selectors and their properties and values.
Inline styles are added differently and I will cover these in detail next week.
Rollover Links
One of the most popular uses of stylesheets is to create mouse rollover effects on links on
your site. They are extremely easy to create and are very versatile. The code you should
insert should either go in a file (saved as a .css) for linked stylesheets or in the <style>
section of your pages:
A:
5
This tells the browser you are making changes to the <a> tag (for links).
link
visited
hover
active
This tells the browser what to do to each type of link (hover is when the mouse is over
the link).
The information inside the {} tells the browser what to apply to each tag.
text-decoration: underline;
text-decoration: none;
This tells the browser whether the text should be underlined or not.
color: #FF0000
This tells the browser the color to make the text (using an RGB code). You can also add:
text-weight: bold;
When you are adding new elements you must always remember to have a ; after each
one.
Inline Styles
Inline styles are added into an HTML tag so that you can just change the content of that
tag. Apart from that, they are used exactly the same as a normal stylesheet. To include
one in your H1 tag for example:
The stylesheet information included is the same as what you would put inside the { } of a
standard stylesheet.
Classes
Another way of making different styles for different parts of your text is to use classes.
These allow you to, for instance, have three different types of <p> tag stylesheet changes
on your site. To do this you give each one a class. This is basically a word which
6
corresponds to a change. For example you could have two classes called 'maintext' and
'footnote' for your <p> tag with different formatting information.
Here are some of the other things you can do to your font's using stylesheets and the code
they require. All of these should be placed inside the { } of your stylesheet or in inline
styles. If you use more than one you should separate each with a semicolon:
This sets the font the text will be displayed in. If the font has more than 1 word in the title
use quotes. Each font should be separated with a comma.
font-size: 16pt;
This is the font size and can be specified using standard point sizes using pt after it or
with one of the following:
px - pixels
in - inches
cm - centimeters
mm - millimeters
font-style: italic;
This either makes fonts italic or normal (by changing italic to normal above)
font-weight: bold;
This makes text bold or normal (as above). You can also use numbers to represent how
bold the text is from 100-900.
7
text-decoration: underline;
As well as putting an underline on your text this can put an overline (a line over the text)
and strike through (using line-through). To take all lines away use underline.
One clever effect you can achieve with stylesheets is to indent text.
text-indent: 1cm
You can use this with the normal units (see part 3). You can also use stylesheets to align
text:
text-align: left
This may not seem particularly special as you can align text with HTML but the benefit
of stylesheets is that now you can use justify as well as left, right and center.
Positioning Objects
You can exactly position anything on a web page, just like in a Desktop Publisher! To do
this you should use:
This would place whatever you applied this to 100 pixels from the top of the page and
100 pixels from the left. Again you can use any of the length units you learned earlier.
You can also use percentage values.
This is an extremely useful tag as it can be used to place objects with precision.
The first, and most simple, color option you can do with stylesheets is to set the text's
color using:
color: #FF0066
This does the same as an HTML color (using HEX) but you can also use the following:
color: RGB(53,36,102)
This specifies the color in RGB values, like in PhotoShop or PaintShop Pro. This could
be very useful if you are trying to match colors.
background-color: #FF0066
8
This will put a background color on a piece of text (like using a highlighter), very useful
for making some of a page stand out. You can also use RGB values for this, like above.
background-image: url(http://www.yourwebsite.com/file.gif)
Instead of applying a background color to some text, this will put a picture in the
background. It works best on a paragraph of text. The image will tile, just like a web page
background.
9
Javascript Tutorial
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.
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.
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 as shown below:
<script language="JavaScript">
JavaScript
</script>
As you can see the JavaScript is just contained in a normal HTML tag set. The next thing
you must do is make sure that the older browsers ignore it. If you don't do this the code
10
for the JavaScript will be shown which will look awful. There are two things you must do
to hide the code from older browsers and show something instead:
<script language="JavaScript">
<!--Begin Hide
JavaScript
// End Hide-->
</script>
<noscript>
HTML Code
</noscript>
As you can see this makes the code look a lot more complex, but it is really quite simple.
If you look closely you can see that all that has been done is that the JavaScript is now
contained in an HTML comment tag. This is so that any old browsers which do not
understand <script> will just think it is an HTML comment and ignore it.
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:
// End Hide-->
There was a:
//
which does not usually appear in an HTML comment. This is because it is the sign for a
JavaScript comment (it was included here to stop the browser from thinking the closing
HTML tag was a piece of JavaScript).
11
JavaScript Alerts, Prompts & Variables
Alerts
alert()
This command will make a popup box appear (click here to see it in action). This can be
useful for warning users about things or (in some cases) giving them instructions. It is
used in the following way:
In the example above single quotations ' was used but you could use double quotations if
you want to ". They work exactly the same way. The reason single quotes was used is
because, later on, when you are using HTML code and JavaScript together you will need
to use them and it is good to be consistent.
<script>
<!-- Start Hide
// End Hide-->
</script>
This is placed between the <head> and </head> tags of the page. As you can see, a
comment tag was used as well as the alert box code. This makes your code more readable
but is not essential.
Variables
my_number
3456
12
Variables can also contain text for example the variable:
my_name
David Gowans
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:
Strings (text):
As you can see a string is included in quotes (either single or double) but a number does
not. If you include a number in quotes it will not be treated as a number. You may also
notice that each line ends with a semicolon. This is standard JavaScript code to show the
end of a line. Always remember to put it in.
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:
// 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
13
This code sets four number variables. It then adds the first and second numbers together
and stores the answer as a variable called new_answer. Then it multiplies new_number
by the third number and stores the answer as answer. Finally, it divides the answer by the
fourth_number to get a new value for the answer.
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:
prompt() command.
For Example,
The text between the first set of quotes is what is written on the prompt box. The text
between the second set of quotes is what is the default text for the input section of the
box.
After this the output string was created. This is done by adding together the input with
two strings declared earlier
As you can see this is much the same as adding 3 numbers together but, as these are
strings they will be put one after the other (you could have also used quotes in here to add
text and strings together). This added the text that had been set as the welcome_text to the
input that was received and then put the closing_text on the end.
Finally the output_text variable was displayed in an alert box with the following code:
alert(output_text);
which, instead of having text defined as the content for the alert box, places the string in
the box.
14
Displaying Information with JavaScript
In the previous section you were shown how to display alert boxes and how to get
information from the user. How variables work was also explained.
document.writeln
This command is very useful as it will output information to a web page. Let us start with
a basic example of how to use it:
document.writeln('Hello there!');
This basically tells the JavaScript to write to the document (web page) on a new line the
text Hello there!. The really useful bit of this is that you can tell the JavaScript to output
text, HTML and variables. First of all you will be shown how to output HTML:
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 we will introduce variables to the script.
Outputting Variables
If you look at the final example that was done in the last part, where we 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, a little more about
where you can put your JavaScript code will be explained.
Up until now all the JavaScript 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. This is demonstrated with the following script.
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. It would be suggested 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:
15
<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');
// 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>
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 example
newsfeed or some counters).
16
To insert a remote JavaScript you do the following:
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.
Browser Windows
Firstly you must know the two ways of creating a link which opens in a separate window.
The most common use is to have:
This is the standard HTML code for opening a new window with the page in it.
This will create a new window, just like the first set of code, but it will also name the
window 'mywindow'. This means that you can then have:
which, when clicked, will change the page which appears in the window you opened.
17
Knowing about how a window name works is very important as you must understand it
to use JavaScript windows effectively.
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:
window.open
For this to work, though, it requires two extra things. Firstly you will need to have some
extra information so that the JavaScript knows how to open the window:
window.open('link.html','mywindow');
This means that a window called 'mywindow' will open with the page link.html in it,
exactly like with the HTML code above.
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.
You will be given 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:
As you can see this is just the same window.open command inside an HTML tag.
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:
window.open('link.html','mywindow','window features');
There are many things you can include here. For example if you wanted a window that
only has a location bar and a status bar (the part at the bottom of the browser) then you
would use the following code:
18
window.open('link.html','mywindow','location, status');
There are many different things you can include in your new window:
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)
This will display the browser toolbar with the Back, Stop, Refresh buttons
toolbar
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
This will show the directories in Netscape browsers like 'Whats new' and
directories
'Whats cool'
You may be a little confused by all these options so you will be shown a few examples of
opening a window in JavaScript:
This window will open with a location bar, toolbar and will be resizable:
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:
window.open('window1.htm','thesecondwindow','height=300,width=200,status,scrollbars'
);
19
Link Events, Image Swaps & The Taskbar
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:
As you can see, one main difference is that the href of the link points to a #. This is
nothing to do with the JavaScript, it just means that, instead of opening a new page, the
link will not do anything. You could, of course, include a link in here and you would be
able to open a new page AND execute some code at the same time. This can be useful if
you want to change the content of more than one browser window or frame at the same
time.
onMouseOver and onMouseOut work in exactly the same way as onClick except for one
major difference with each.
onMouseOver, as the name suggests, will execute the code when the mouse passes over
the link. The onMouseOut 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 and when the mouse moves over the link it changes the image
which is displayed.
20
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:
The name for the image could be anything and, like the window names from the last part,
is used to refer to the image later on.
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:
<a href="#"></a>
The following code will make a mouseover on your image (assuming you inserted the
image as shown above and called your mouseover image homeon.gif):
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 that 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.
21
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:
You can include this in standard code, onClick, onMouseOver or onMouseOut. This
allows you to do things like display a description of a link when the mouse moves over it.
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).
As you can see this could be very useful for many sites. The code is as follows:
This code is made up of three main parts. The first part which gets the guess from the
user, you have used before. This is followed by:
if(guess ==5)
Which is quite self explanatory. It checks to see if the variable guess is equal to 5. The if
statement is followed by:
{
alert('Correct! I was thinking of 5');
}
The important part of this is the curly brackets round the alert command. These contain
the code which should be executed if the if statement returns 'true' (in this example if
22
guess equals 5). The final part is the:
else
{
alert('Wrong! I was thinking of 5');
}
This tells the browser that if the if statement does not return 'true' (in this example if
guess does not equal 5) to execute the code between the curly brackets.
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:
if(variable == variable)
As well as doing this you can check to see if one variable is greater than another, less
than another or not the same as another:
if(variable != othervariable)
If variable is not equal to other variable
These can be very useful in your web pages. You can also check to see if two conditions
are true before executing code using &&:
This will only execute its code if variable1 is equal to variable2 and is less than variable3.
You can also run the code if one of the conditions is true:
23
if(variable1 == variable2) || (variable1 < variable3)
This will only execute its code if variable 1 is equal to variable to or is less than
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':
This will continuously loop the code inside the { } until the test input does not equal
password is false (the password is correct).
For Loops
For loops are used to do something a set number of times. For example:
document.writeln(loop);
}
This will start by setting the variable loop to 0, it will then loop, adding one to the value
each time (using the loop++ code) as long as loop is less than 11. They take the form:
24
Forms & Functions
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. This will be quickly explained.
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):
<form name="formname">
</form>
Once you have this you can create your first JavaScript to refer to a form:
Move the mouse over here to add some text to the box
This is done very easily using the onMouseOver property of the link. It can refer to the
text box as follows:
window.document.example1.first_text.value='Hi there';
This tells the browser to put 'Hi there!' into the value of the item called 'first_text' in the
form called 'example1'.
You can also do this with multiline text boxes. You can use
/n
to start a new line.
In this section, you have learnt the most important part of this lesson, how to refer to an
item in a form.
25
Events
Just like links, you can set events for items in a form. They are:
These are placed into the code as part of the form's item for example:
JavaScript Functions
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.
function functionname(parameters)
{
For a very basic function you need no parameters and it would be constructed like this (in
the <head> of the document):
function sayhi()
{
alert(Hi there!);
}
Which would display the alert whenever the mosuse passed over it. Unless you are
repeating something many times, though, this will not seem particularly useful. This is
where parameters become useful.
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:
26
function say(what)
{
alert(what);
}
What this is doing is the information in the brackets is passed to the function. In the
brackets of the function is the word 'what'. This is telling the JavaScript to assign the
information in the brackets to the variable what (the same as var what='something';). You
can even do this with multiple pieces of information by separating them by commas.
More 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 PHP 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:
Submit
What this code does is tell the JavaScript that when the form is submitted it should do
nothing. This stops the browser from refreshing the page (as it would do if there was just
a submit button and the form had no action). Now what you can do is to call a function
using the submit button:
Which will tell the browser to run the function 'MyFunction' when the Submit button is
clicked. You can, of course, use this without the:
27
return false;
part. This would be useful if, for example, you want to validate a form before it is sent to
a PHP script. You would include the form's action as normal. Then, in the onSubmit part
you would call your function to check what had been entered.
Checkboxes
Checkboxes and radio buttons are two of the remaining form items. First we will cover
checkboxes.
Unchecked Box
Checked Box
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.
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!');
}
I will now explain what this code does. It will check the value of the checkbox. If the
value is ture (which means the checkbox is checked) then it will display an alert box
which will tell you the box is checked. If it is not checked it will check the box (put a
checkmark in it) and tell you what it has done.
If, of course, you want to check or refer to the unchecked value of a checkbox the code
would be:
window.document.example1.my_checkbox.checked=false;
Remember that, when referring to check boxes you do not need to inclose true or false in
quotations.
As with all other form objects you can use onBlur, onChange and onFocus.
28
Radio Buttons
Blue
Red
Green
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.
The two remaining form elements are selects and menus. We 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 let us see a quick example of a menu in action
and the code for it. For a select box we would just change the height property. The code
used is below:
What this code is doing is, when the select is changed it is telling the page in the browser
to change its location to the value of the select box. The location of the document is
accessed using:
window.document.location
As you can see, this is could be very useful, both for getting feedback from visitors and
for redirecting them (as in the example above).
Conclusion
In this tutorial we 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
29
JavaScript left to learn with many more advanced commands. 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.
30