BISI 4400
JS Handout 2
EVENTS
Events are actions that can be detected by javascript.
An example would be the onmouseover event, which is detected when the user moves the mouse over an object.
Another event is the onload event, which is detected as soon as the page is finished loading.
Usually, events are used in combination with functions, so that the function does not start until the event happens.
The following are the most important events recognized by javascript:
Event / Detected when / HTML tagsonfocus="" / Form field gets focus / select, text, textarea
onblur="" / Form field looses focus / select, text, textarea
onchange="" / Content of a field changes / select, text, textarea
onselect="" / Text is selected / text, textarea
onmouseover="" / Mouse moves over a link / A
onmouseout="" / Mouse moves out of a link / A
onclick="" / Mouse clicks an object / A, button, checkbox,
radio, reset, submit
onload="" / Page is finished loading / body, frameset
onunload="" / Browser opens new document / body, frameset
onSubmit="" / Submit button is clicked / form
Events are used for two main purposes:
- To perform a function upon detection of the event,
- To show a popup box upon detection of the event.
Below is a brief description of the main purposes for each event.
onFocus, onblur and onchange are mainly used in combination with validation of form fields.
Lets say you had a function called validateEmail() that would check to see if an entered email address has an @ in it, and if it has a meaningful end, such as "com", "net" or whatever. Furthermore, suppose the user could enter his email address in a form.
You would then use the onchange event to call the function whenever the user changes the content of the field:
onload and onunload are mainly used for popups that appear when the user enters or leaves the page.
Another important use is in combination with cookies that should be set upon arrival or leaving your pages.
For example, you might have a popup asking the user to enter his name upon his first arrival to your page. The name is then stored in a cookie. Furthermore, when the visitor leaves your page a cookie stores the current date.
Next time the visitor arrives at your page, it will have another popup saying something like: "Welcome Bill Clinton, this page has not been updated since your last visit 8 days ago".
Another common use of the onLoad and onunload events is: Some annoying pages have a function that immediately opens several other windows as soon as you enter the page. This is a clear break of netiquette, and is not considered proper webdesign.
onsubmit is used for one major purpose: To validate all fields within a form before actually submitting it.
Sometimes however, the visitor might find it annoying to have validations in the middle of entering fields on a form. Rather than validating after each input, you might want the form to be validated only upon clicking the submit button.
This can be done using the onsubmit event.
Assume you made a function named checkform() that would validate entries to a form.
Now you want this function to be called when the user clicks the submit button.
If the content is not accepted by your function the submit should be cancelled.
This way nothing would be submitted unless your function accepted the content.
What you should do, is: add an onsubmit event to the <form> tag this way:
The function checkform() returns either true or false.
If it returns true the submit will take place.
If it returns false the submit will be cancelled.
onmouseover and onmouseout are mainly used for one purpose: To create animated buttons.
You may have noticed that these events can only be used in combination with the link tag <a>.
However, the events are often more useful in combination with the image tag <img>. The trick to making the event work on an image is simply to turn the image into a link. (If the image is not supposed to actually work as a link, you could always make it link to an empty anchor, as shown in the example below).
HTML example:
<a href="#" onmouseover="alert('I detected an onmouseover event'); return false" onmouseout="alert('I detected an onmouseout event'); return false"<img src="rainbow.gif" width="60" height="60">
</a>
Note: The href="#" links the image to nowhere. If you really wanted the image to link to a page you should enter the address of the page here instead.
VARIABLES
Variables can be compared to small boxes with names.
If you were to store 5 pair of shoes, you might have a box for each pair. On each box you would write what is in it.
- The boxes would be your variables.
- Places to store things. - The name on the boxes would be the variable names.
- The ones you'd use when referring to each of the boxes. - And finally the shoes, would be the content of the variables.
- What is stored in the boxes.
A variable is simply a place in the computer's memory to store information. All variables are referred to by the unique name you assigned to them.
Consider this example:
<html><head>
<title>My Javascript Page</title>
</head>
<body>
<script>
myname="Henrik";
document.write(myname);
</script>
</body>
</html>
This example would write "Henrik" in the document.
Look at this example to see the importance of this.
<html><head>
<title>My Javascript Page</title>
</head>
<body>
<script>
Henrik="my first name";
myname=Henrik;
document.write(myname);
</script>
</body>
</html>
Try to predict the output of the example before reading on.
- In the first line, the text "my first name" is stored in the Henrik variable.
- In the second line, the Henrik variable is stored in the myname variable.
- Finally in line 3, the myname variable is written to the document.
The result is that "my first name" will be written on the page.
Naming VARIABLES
It is important to know the proper syntax to which variables must conform:
- They must start with a letter or underscore ("_")
- Subsequent characters can also be digits (0-9) or letters (A-Z and/or a-z). Remember, JavaScript is case-sensitive.
Valid variable names
my_name
invoice2
_total
Average
Invalid variable names
100_numbers(name starts with a numeral)
rate%_of_inflation(non legal character)
Declaring and Assigning Values to Variables
To create a variable, the var keyword precedes the variable name, and is used only once for declaration. All future references to the variable are made without the var keyword.
The most common way to assign a value to a variable is using the equals sign.
Examples
var myVarName // declare variable, has null value
myVarName = 162 // assign a value, null value is replaced
//OR
var myVarName = 162 // declare AND assign value (initialize)
myVarName = "two hundred" // the value can be changed later on, even to a different type of value
var time,dog,baby //multiple variables may be declared simultaneously
var time = 1, dog = "hairy", baby = true //multiple variables may be initialized simultaneously
ARITHMETHIC OPERATORS
The above table includes the so-called "arithmethic operators" a++ and a--.
You could really live well without these, since what they do can be achieved by using the other operators available.
However you will often see them used in scripts, and you might even be lazy enough to use them yourself, since it is faster to type a++; than it is to type a=a+1;.
++ / increment / a=5;
a++;
a would now equal 6
-- / decrement / a=5;
a--;
a would now equal 4
% / returns modulus,
which is what is left when
two numbers are divided. / a=8 % 3;
a would now equal 2,
since 8 can be divided
by 3 two times leaving
a remainder of 2.
This table contains the different comparing operators:
Operator / Explanation / Example== / equal to / 4==5 (false)
5==5 (true)
5==4 (false)
!= / not equal to / 4!=5 (true)
5!=5 (false)
5!=4 (true)
less than / 4<5 (true)
5<5 (false)
5<4 (false)
greater than / 4>5 (false)
5>5 (false)
5>4 (true)
<= / less than or equal to / 4<=5 (true)
5<=5 (true)
5<=4 (false)
>= / greater than or equal to / 4>=5 (false)
5>=5 (true)
5>=4 (true)
IF AND ELSE
Sometimes javascript requires the ability to make distinctions between different possibilities.
For example, you might have a script that checks which browser the user arrives with. If it's MSIE, a page specifically designed for that browser should be loaded, if it's Netscape another page should be loaded.
The general syntax for if statements is:
if (condition) {action1} else {action2};
An example could be:
else {alert("You are using Netscape")};
Again it is important to note that if is written as "if".
Using the capital "IF" would cause an error.
Also note that when comparing variables you will need to have two equals signs next to each other (==).
If we wrote browser="MSIE" we would actually store "MSIE" in the variable called browser.
When you write browser=="MSIE" javascript knows that you want it to compare rather than assign a value.
More complex if statements can be made by simply entering new if statements in the else part:
if (condition) {action1}
else {if (condition) {action2} else {action3};};
An example:
else {if (browser=="Netscape") {alert("You are using Netscape")}
else {alert("You are using an unknown browser")};};
AND, OR & NOT
To further enhance your if statements you can use the so-called logical operators.
And is written as and is used when you want to check if more than one condition is true.
Ex: If the basket contains egg and the basket contains bacon, we can have egg and bacon.
The syntax is: if (condition condition) {action}
Or is written as || and is used when more than a one condition should result in the check being true. (|| is achieved by using the shift key combined with the \ key)
Ex: If the basket contains milk or the basket contains water, we can have something to drink.
The syntax is: if (condition || condition) {action}
Not is written as ! and is used to invert the result.
Ex: If not the basket contains egg or not the basket contains bacon, we cant have egg and bacon.
The syntax is: if (!(condition)) {action}
LOOPS
Imagine that you wanted a script to perform the same routine over and over again 50 times in a row.
An example could be if you wanted a script to produce a table comparing temperatures in Fahrenheit and Celsius.
The script should produce 50 lines in a table showing different temperatures according to the two scales.
Instead of adding 50 almost equal lines in your script you could use loops to make the script perform a task like this.
There are two different kinds of loops: for and while.
The for loop is used when you know in advance how many times the script should perform.
For example if you wanted it to create exactly 50 lines.
The while loop is used when you want the loop to continue until a certain condition becomes true.
For example, if you wanted to make a table comparing Celsius and Fahrenheit, stepping 15 degrees for each row, and you wanted the table to contain values up to 1200 degrees of Celsius.
Below is a description of each of these two loops:
FOR LOOPS:
SYNTAX:
{
// Here goes the script lines you want to loop.
}
Enter a variablename where it says variable.
Enter the startvalue of the loop where it says startvalue.
Enter the endvalue of the loop where it says endvalue.
Enter the factor each loop should increment where it says incrementfactor.
Note: The incrementfactor could be negative if you wanted.
Furthermore the <= could be any comparing statement, ex. , == or whatever.
EXAMPLE:
<head>
<title>Celsius-Fahrenheit Converter</title>
</head>
<body>
<table border=3>
<tr<td>CELSIUS</td<td>FAHRENHEIT</td</tr>
<script language="javascript">
for (celsius=0; celsius<=50; celsius=celsius+1)
{
document.write("<tr<td>"+celsius+"</td<td>"
+((celsius*9/5)+32)+"</td</tr>");
}
</script>
</table>
</body>
</html>
WHILE LOOPS:
SYNTAX:
{
// Here goes the script lines you want to loop.
}
Enter a variablename where it says variable.
Enter the endvalue of the loop where it says endvalue.
Note: The <= could be anything that would fit the purpose ex. , == or whatever.
EXAMPLE:
<head>
<title>Celsius-Fahrenheit converter</title>
</head>
<body>
<table border=3>
<tr<td>CELSIUS</td<td>FAHRENHEIT</td</tr>
<script language="javascript">
celsius=0;
while (celsius<=50)
{
document.write("<tr<td>"+celsius+
"</td<td>"+((celsius*9/5)+32)+"</td</tr>");
celsius=celsius+1;
}
</script>
</table>
</body>
</html>
BREAK & CONTINUE
Two special commands can be used in loops: break and continue.
break simply breaks the loop and continues with what might follow after the loop.
An example would be if you had a loop calculate the squareroot of numbers decrementing from 50.
Since calculating the square root of a negative number is an illegal mathemathic operation you would like the loop to end when the square root of zero had been calculated.
To do this you would add this inside your loop:
continue breaks the current loop and continues with the next value.
An example would be if you had a loop that divided a certain value with a factor of numbers ranging from -50 to +50.
Since division by zero is an illegal mathemathic procedure the loop would look like this:
{
if (value==0) {continue};
document.write((100/value)+"<br>");
}
FUNCTIONS
Instead of just adding your javascript to the page and having the browser perform the tasks as soon as the script is read, you might want your javascript to be performed only upon the detection of a certain event.
For example, if you made a javascript code that changed the background color of the page when the user clicked a button, then you would need to tell the browser, that the script should not be performed right away when loaded.
To keep the browser from performing a script as soon as it is loaded you need to write the script as a function.
Javascript written into functions will not be performed until you specifically ask for it. This way you gain complete control of the timing.
Look at this example of script lines written as a function:
<head>
<script>
function myfunction()
{
alert("Welcome to my world!!");
}
</script>
</head>
<body>
<form name="myform">
<input type="button" value="Hit me" onclick="myfunction()"
</form>
</body>
</html>
The general syntax for a function is:
function functionname(variable1, variable2,..., variableX)
{
// Here goes the javascript lines for the function
}