Search
Sponsors

Archive for the ‘Tutorials’ Category

Embedding JavaScript

Saturday, January 10th, 2009

There are several ways to embed JavaScript into your HTML pages . Lets look at them

the <SCRIPT> tag .

JavaScript code appears between a <SCRIPT> and a </SCRIPT> tags . You can use just the basic <SCRIPT> tags for your scripts like the following

<SCRIPT>
document.write(”A JavaScript example “);
</SCRIPT>

which gives us the following output

document.write(”A JavaScript example “);
there are a number of attributes which we can use with the <SCRIPT> tag

LANGUAGE

This is used to specify what scripting language the script is written in . In the majority of browsers the default attribute is JavaScript . But you have to be aware that there is also VBScript as well . If you were to mix VBScript and JavaScript and didn’t specify the language you would get some interesting problems cropping up . You can set the LANGUAGE attribute to the actual version number of JavaScript so if you set it to JavaScript 1.1 you would get all of the features of JavaScript 1.1 but if your script had features that were introduced in a later version of JavaScript the script would fail .

SRC

this is used to specify the URL of an external script to be loaded and executed . These external files usually have a .js extension . So this would look like this <SCRIPT SRC = “sample.js”></script>

ARCHIVE

this is used to specify the URL of a JAR file that contains a script specified by the SRC attribute . JavaScript 1.2 required.

TYPE

This is only supported in Internet Explorer 4 and Netscape Navigator 4 upwards . The syntax is as follows

<SCRIPT TYPE = “text/JavaScript”>my javascript </SCRIPT>

Event Handlers

JavaScript code can also be put into the handler attributes of HTML tags . These attributes always begin with on and some examples are onClick , onBlur and onMouseDown . The code is executed when the event occurs so for example if you press a button and have JavaScript code attached to the button this will execute when the button is pressed . Here is an example .

Here is the HTML for this example

<INPUT TYPE = button VALUE = “Press me for an alert box”
onClick=”alert(’damn annoying alert box example’);”>

JavaScript URLs

A JavaScript URL is a special type of URL . A JavaScript URL does not send or retrieve any information like a normal URL except as a side effect A JavaSCript URL is used to execute a script . JavaScript URLs occupy a single line , so if the contain more than one statements , semi-colons should be used .

Here is an example

alert box example here is the HTML code for this stunning example

<a href=”javascript:alert(’another annoying alert box’)”>alert box example</a>

Escape sequences

Saturday, January 10th, 2009

Here is a table listing the special escape sequences.

Escape

represents

\b

BackSpace

\f

Form feed

\n

NewLine

\r

Carriage Return

\t

Tab

\’

Single quote

\”

double quotes

\\

single backslash

\ddd

character with Latin-1 encoding specified by three octal digits ddd

\xdd

character with Latin-1 encoding specified by two hexadecimal digits dd

\udddd

character with unicode encoding specified by four hexadecimal digits dddd

\n

n , where n is any character other than the ones above.

Data types

Saturday, January 10th, 2009

Numbers

In JavaScript all numbers are treated as floating point numbers . JavaScript does support integers , octal numbers , hexadecimal numbers etc but at the lowest level , JavaScript sees all numbers as floating point numbers .

Integers

These are numbers with no fractional parts , they can be positive or negative and they can be decimal , hexadecimal or octal . The most common type of integers are decimal integers (or base 10 ) . these are numbers ranging from 0 - 9 and cannot have a 0 in front of the numbers . Here are some examples .

valid : 2 , 23 , 900 , 54

invalid : 04 , 0300 , 079

Octal integers (also referred to as base-8 ) must begin with a leading zero and then each digit after the leading zero can be in the range of 0 - 7.

hexadecimal integers (also known as base-16) must begin with 0x or 0X . Each digit following this can be in the range of 0 - 9 and from a - f where a - f is the equivalent of 10 - 15 .

Example

A simple example here

<!–
document.write(”45 is ” + 45 + ” decimal (base 10)”);
document.write(”<br>045 is ” + 045 + ” octal (base 8)”);
document.write(”<br>0×45 is ” + 0×45 + ” hexadecimal (base 16)”);
//–>
<script language = “JavaScript”>
<!–
document.write(”45 is ” + 45 + ” decimal (base 10)”);
document.write(”<br>045 is ” + 045 + ” octal (base 8)”);
document.write(”<br>0×45 is ” + 0×45 + ” hexadecimal (base 16)”);
//–>
</script>

<!–
document.write(”45 is ” + 45 + ” decimal (base 10)”);
document.write(”<br>045 is ” + 045 + ” octal (base 8)”);
document.write(”<br>0×45 is ” + 0×45 + ” hexadecimal (base 16)”);
//–>
now can you see the importance of not putting 0 or 0x in front of your numbers , the results are different in octal and hexadecimal.

Strings

A string is made up of a number of characters . Strings are declared by placing the characters inside either double quotes ( ” ” ) or inside single quotes( ‘ ‘ ) . When a backslash character(\) appears in a string literal , it escapes the character that follows it this means you can place special characters in the string . ( see our special characters reference )

Boolean

A boolean data type can only have two values either true or false . These are often represented by 1 for true and 0 for false in javaScript . It is sometimes better to think of true or false as on or off or even as yes or no .

null

This is provided by the JavaScript keyword null which represents a condition where no value exists .

Naming Variables

There are some guidelines to follow when naming variables in JavaScript . These are as follows

The first character of the name must be a letter or an underscore ( _ )

All characters following the first character can be letters , underscore , or digits

Letters can be either upper or lower case . Note that JavaScript treats the two cases differently so for example firstname is different from FirstName or FIRSTname .

Assigning Variables

To declare a variable in JavaScript we use the var keyword followed by a variable name . You can put multiple variables using the same var keyword if this is the case you use commas to separate the variable names .

Now that you have defined a variable , you can assign a value to it with the assignment operator (=) . Often the declaration and assignment take place at the same time . If a value is assigned to a variable that has not been declared with the var keyword . JavaScript creates a global variable .

Lets see an example of all this .

<script language = “JavaScript”>
<!–
//variable declaration with no assignment
var name ;
//assignment with no use of var keyword
name = “iain”;
//variable declaration and assignment combined
var age = 29 , height = 6;
//print details
document.write(name ,” is “, age ,” and ” ,height, ” foot ” );
//–>
</script>

Which gives this result .

<!–
//variable declaration with no assignment
var name ;
//assignment with no use of var keyword
name = “iain”;
//variable declaration and assignment combined
var age = 29 , height = 6;
//print details
document.write(name ,” is “, age ,” and ” ,height, ” foot ” );
//–>

Variable Scope

Variables in JavaScript can be either local or global . All variables are global unless they are declared in a function in this case the variable is local to that function . You can have two variables with the same name if one is global and one is local to a function . When you access the variable in the function you access the local variable , from outside the function you are accessing the global variable .

You should always use the var keyword to declare a variable inside a function if you wish it to be a local variable . If you do not JavaScript creates a global variable.

looping in JavaScript

Saturday, January 10th, 2009

These are times when the same portion of code needs to be executed many times with different values .

for

The for structure loops a preset number of times . The for loop is made up of two parts the condition and statements . The condition portion of the structure determines how many times the loop repeats while the statement is what is executed every time the loop occurs.

The conditional structure is contained within parentheses and is made up of three parts , each separated by a semi colon ( ; ) . The first part of the condition structure initializes a variable to a starting value . In most cases , the variable is declared here and initialized . The second part is the actual conditional statement that determines how many times the loop with be iterated . The third and final part determines how the variable which was initialized in the first part , should be changed each time the loop is iterated . The third part causes the variable to be incremented , decremented etc . Here is the syntax of the for loop

for (initialize ; condition ; adjust)
{
statement ;
}

You have to beware of infinite loops . Lets look at a for loop example .

<script language =”JavaScript”>
<!–
for(var i = 0 ; i <= 10 ; i++)
{
document.write(” ” , i );
}
//–>
</script>

which gives us the following result

<!–
for(var i = 0 ; i <= 10 ; i++)
{
document.write(” ” , i );
}
//–>
while

The while loop is similar to the for loop . The statement works like this while the expression in brackets is true execute the statements in the loop . Once the last statement is executed return to the top of the loop and evaluate the expression again . When the expression evaluates to false the next line of code after the while loop structure executes . To prevent infinite loops a statement must be included in the loop that modifies a variable in the expression . Here is the syntax of the while loop .

while (expression)
{
statement;
}

Here is an example

<script language=”JavaScript”>
<!–
var i = 0;
while(i <= 10)
{
document.write(” ” , i);
i++;
}
//–>
</script>

which gives us the following results

<!–
var i = 0;
while(i <= 10)
{
document.write(” ” , i);
i++;
}
//–>
do while

This loop is simply a variant of the while loop . The important difference is that the loop will always evaluate once before evaluating the expression for the first time . Here is the syntax.

do
{
statement ;
}
while (expression);

Once the loop has executed for the first time the expression in brackets is evaluated . If this is true the loop is executed once again . If this is false the next of line of code after the while structure is executed . A statement must be included within the loop that modifies a variable in the expression to prevent infinite loops .

Here is the example above modified to use a do … while loop

<script language=”JavaScript”>
<!–
var i =0;
do
{
document.write(” ” , i);
i++;
}
while(i <=10);
//–>
</script>

and here is the result again
<!–
var i =0;
do
{
document.write(” ” , i);
i++;
}
while(i <=10);
//–>

for .. in

This is not the same as the for loop . The for…in loop is used to provide access to the enumerated properties of a JavaScript object . This loop is only found in JavaScript . The statement in the loop are executed for each property of an object until every property has been accessed. The syntax looks like this

for ( variable in object)
{
statement ;
}

Here is an example that accesses all the properties of the document object

<script language=”JavaScript”>
<!–
var i;
for(i in document)
{
document.write(” ” ,i);
}
//–>
</script>

and here is the result
<!–
var i;
for(i in document)
{
document.write(” ” ,i);
}
//–>

Break / Continue

Break is used to terminates execution of the innermost enclosing loop and from JavaScript 1.2 onwards you can also name the loop.

break ;
break label ;

Continue is restarts the innermost loop or from JavaScript 1.2 onwards can actually restart a named loop .

continue;
continue label;

Translate