Web Design & Development

[Web Design and Development Topics] [Javascript List]

Javascript Basics

FUNCTIONS

A function accepts parameters and returns a value. You can create your own functions or use some standard built-in functions of Javascript. Functions are commonly used as a shortcut to repeated activities where you pass variables into the function. To use a function you simply include the function name and follow it with the parameters in parentheses.

Some built in functions include:
· parsetInt - converts strings to integers
· parseFloat - converts strings to floating-point numbers
· eval - evaluates Javascript expressions

However, you can also define your own functions with the function keyword. Here is an example that adds two numbers:

<script type="text/javascript">
<!--//
function Add(a,b) {
var result = a + b;
return result;
}
var test = Add(2,4)
document.write("two plus four equals: ", test);
//-->
</script>

To use this function we include the functions name, followed by the parameters in parenthesis.

Notice the semicolon at the end of the example statement. This is a common feature in many languages including C and Java to indicate the end of a statement. Javascript does not require them but they do add clarity.

When you declare a function the Javascript interpreter stores it and prepares it for use, but it is not executed until a call is made for it. By convention, the proper place to define a function is in the <head> section, although it doesn't have to be. The function call, on the other hand, should be included in the <body> of the HTML document so that the results can be displayed.

Sample of a call function:

<head>
<script type="text/javascript">
function myfunction()
{
alert("HELLO")
}
</script>
</head>
<body>
<form>
<input type="button"
onclick="myfunction()"
value="Call function">
</form>
</body>
</html>

VARIABLES

A "variable" is simply a container or bucket for information you want to store. In other words, a variable is simply a name given to a value.

Variable sample:

This example declares a variable, assigns a value to it, and then displays the variable twice - once as plain text and once as header1.</p>

<script type="text/javascript">
var sample = "Daffy Duck"
document.write(sample)
document.write("<h1>"+sample+"</h1>")
</script>

A variable's value can change during the script. You can refer to a variable by name to see its value or to change its value.

STRONGLY TYPED VERSUS LOOSELY TYPED VARIABLES

Programming languages such as C and Java use "strongly typed" variables. This means that variables can hold a very specific type of value. You have to declare the type of data a variable can hold when you define it, and you must use conversion functions when you wish to change the variables type.

Javascript, on the other hand, is a "loosely typed" language - when you declare a variable you don't have to define its type. Javascript assumes it for you. Also, conversions between variable types happen automatically.

EXAMPLE OF LOOSELY TYPED VARIABLES

Lets say you start out with two statements:
total = 10;
title = dogs

Javascript assumes total is an integer and title is a string.

Now lets say you add .25 to the total by typing:

total += .25;

The total is now automatically changed to a floating-point from an integer and its value is now 10.25

Now what if you said:

total = total + title

Well, total could no longer be a floating point, so the variables are converted to match. Javascript then assumes both the original total and description are both strings. Thus instead of addition it concatenates the results so you end up with a string variable that says "10.25 dogs"

NAMING AND DECLARING VARIABLES (IDENTIFIERS)
VARIABLE SCOPE

EXPRESSIONS

An expression is something that Javascript interprets before using it in a statement.

<body>
<script type="text/javascript">
var car1 = "Honda";
var car2 = "Chevy";
document.write('<p>car1: ' + car1 + '<br>car2: ' + car2 + '</p>');
</script>
</body>

OBJECTS

An object is a more complicated version of a variable that can store multiple values; they commonly combine data with functions. Javascript also includes objects that enable you to access features of the browser directly such as windows, documents, frames, forms, links, and anchors. An object includes properties, which hold the data. In addition, it can include methods, functions to act on the data.

Dates and Times (Date Object) Sample:

<script type="text/javascript">
var d = new Date()
document.write("Date: ")
document.write(d.getDate())
document.write(".")
document.write(d.getMonth() + 1)
document.write(".")
document.write(d.getFullYear())
document.write(" Time: ")
document.write(d.getHours())
document.write(".")
document.write(d.getMinutes())
document.write(".")
document.write(d.getSeconds())
</script>

Some of the date object methods:

date()
getDate()
getDay()
getMonth()
getYear()
getFullYear()
getHours()
getMinutes()
getSeconds()

setDate()
setDay()
setMonth()
setYear()
setFullYear()
setHours()
setMinutes()
setSeconds()
toString()

USING COMMENTS

· A single line comment begins with two slashes (//) and ends at the end of the line
· A multiple line comment begins with the /* delimiter and ends with the */ delimiter.

Sample (must be within the <script> tags):

// single line comment

/* this is
more than
one line */

ARRAYS

Arrays are commonly a numbered set of variables. Javascript does not support arrays as variables, instead they are handled as "objects". An Array object is used to store a set of values in a single variable name. Each value is an element of the array and has an associated index number.

For example, the below statement creates an array called scores with 10 values:

scores = new Array(10);

Once you define the array you can access its elements by using brackets to indicate the index. For example, to assign values to the first and third scores:

scores[0] = 25;
scores[2] = 29;

Note: Javascript array indices begin with a zero. Thus a ten element array would have indices from 0 to 9.

Sample Array

<script type="text/javascript">
var famname = new Array(6)
famname[0] = "Aspen"
famname[1] = "Pine"
famname[2] = "Maple"
famname[3] = "Spruce"
famname[4] = "Willow"
famname[5] = "Burr Oak"

for (i=0; i<6; i++)
{
document.write(famname[i] + "<br />")
}
</script>

Some things you can do with arrays:

concat() - Returns an array concatenated of two arrays
join() - Returns a string of all the elements of an array concatenated together
reverse() - Returns the array reversed
slice() - Returns a specified part of the array
sort() - Returns a sorted array

OPERATORS

Tools used to create an expression are operators. Operators are used to operate on values.

Javascript operators include the following:

OPERATOR PRECEDENCE (HIGHEST PRECEDENCE ON TOP) UNLESS SPECIFIED

The following list of operators was taken from http://www.w3schools.com/js/js_operators.asp

Arithmetic Operators

Operator Description Example Result
+ Addition x=2
x+2
4
- Subtraction x=2
5-x
3
* Multiplication x="4"
x*5
20
/ Division 15/5
5/2
3
2.5
% Modulus (division remainder) 5%2
10%8
10%2
1
2
0
++ Increment x=5
x++
x=6
-- Decrement x=5
x--
x="4"

Assignment Operators

Operator Example Is The Same As
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y x=x%y

Comparison Operators

Operator Description Example
== is equal to 5==8 returns false
!= is not equal 5!=8 returns true
> is greater than 5>8 returns false
< is less than 5<8 returns true
>= is greater than or equal to 5>=8 returns false
<= is less than or equal to 5<=8 returns true

Logical Operators

Operator Description Example
&& and x=6
y=3

(x < 10 && y > 1) returns true

|| or x=6
y=3

(x==5 || y==5) returns false

! not x=6
y=3

!(x==y) returns true

String Operator

A string is most often text, for example "Hello World!". To stick two or more string variables together, use the + operator.

txt1="What a very"
txt2="nice day!"
txt3=txt1+txt2 

The variable txt3 now contains "What a verynice day!".

To add a space between two string variables, insert a space into the expression, OR in one of the strings.

txt1="What a very"
txt2="nice day!"
txt3=txt1+" "+txt2ortxt1="What a very "
txt2="nice day!"
txt3=txt1+txt2

The variable txt3 now contains "What a very nice day!".

CONDITIONALS AND LOOPS

CONDITIONAL EXPRESSIONS

If something is true then do one thing, if it is false then do something else. The value after the question mark will be used if the condition is true, and the value after the colon will be used if the condition is false.

Sample:
value = (a == 1) ? 1 : 0

What this means in a traditional "if" statement is:

if (a == 1)
value = 1;
else
value = 0;

IF..ELSE

The if statement is the main conditional statement in Javascript. It has an optional else keyword which can specify a block of statements to execute if the condition is not true.

For example:
if (a =="1") {
document.write ("I found 1")'
a = 0; //resets a to zero
}
else {
document.write ("Incorrect value: " + a);
a = 0;
}

Sample of If...Else:

<script type="text/javascript">
var d = new Date()
var time = d.getHours()

if (time < 10)
{
document.write("<b>Good morning</b>")
}
else
{
document.write("<b>Good day</b>")
}
</script>

LOOPS

Looping statements in Javascript are used to execute the same block of code a specified number of times.

FOR

This is the first tool to look at for creating loops. A for loop typically uses a variable (called a counter or an index) to keep track of how many times a loop has executed, and it stops when the counter reaches a certain number. A basic for statement looks like this:

for (var = 1; var < 10; var++) {

Sample of "for" loop:

<script type="text/javascript">
for (i = 0; i <= 5; i++)
{
document.write("The number is " + i)
document.write("<br />")
}
</script>

WHILE

The other keyword for loops after "for" is while. While loops don't necessarily use a variable to count. Instead, they execute as long as the while condition is true. If the condition starts out false the statements might not execute at all. A sample:

while (total < 10) {

Sample of "while" loop:

<script type="text/javascript">
i = 0
while (i <= 5)
{
document.write("The number is " + i)
document.write("<br />")
i++
}
</script>

WINDOWS DISPLAYING HTML

Often users want the link to pop open a new window with specific settings either automatically or on a mouse click. This can be accomplished with Javascript.

Example:

<script type="text/javascript">
<!--//

function show_it()
{
var win2= window.open ("http://www.yahoo.com", "second",
" location=yes, resizable=yes, height=200, menubar=yes, toolbar=yes, scrollbars=yes, width=200")
}

//-->
</script>
<a href="#", onclick=show_it()>
Very small yahoo pop up</a>

Note: if all you want is a new window to pop up you can just add "target="_blank"" to the a hef code such as in: <a href="http://www.google.com" target="_blank">DEMO</a>

WARNINGS AND DIALOGUE BOXES

Three are three types of popups custom-made for Javascript that are created with methods of a Window object: alert (just has "ok"); confirm ("ok" or "cancel"); and prompt (text box).

Sample of each type of popup:

<script type="text/javascript">
var agree = false, notes = '';
agree = confirm ('Do you love programming?');
if ( agree )
notes = prompt ("Its good points?", 'Type here');
else
notes = prompt ("Its bad points?", 'Type here');
alert (notes + '\nYour mother would be proud.');
</script>

HISTORY

History stores the URL's of all the past documents appearing in the window or frame. You can navigate forwards and backwards through the list of URL strings.

Samples (do not have to be within <script> tags as they are event handlers):


<a href="#" onClick="history.back();">Boldly take a step back</a><br />
<a href="#" onClick="history.go(-2);">Boldly take 2 steps back</a><br />
<a href="#" onClick="history.forward();">Boldly go forward if you can</a <br />
<a href="#" onClick="window.location.replace('http://www.amazon.com');">Boldly forget the past</a>

DOCUMENT

These represent characteristics and attributes of the current HTML page. It has properties (attributes of the object) and methods (allowing the object to do something).

DOCUMENT PROPERTIES

<html>
<head>
<title>my title</title>
</head>

<body>
Last modified :
<script type="text/javascript">
document.write(document.lastModified);
document.write("<br/>Title of page: ");
document.write(document.title);
</script>
</body>
</html>

DOCUMENT METHODS

Sample of using document.write and document.location.href:

<script type="text/javascript">
<!--//
document.write("This document is located at: "+ document.location.href);
//-->
</script>

Sample of making it so the user can't go "back":

<script type="text/javascript">
<!--//
history.go(-history.length);
document.location = 'http://www.hotbot.com';
//-->
</script>

Drawbacks of JavaScript