///Introduction to JavaScript Tutorial

Introduction to JavaScript Tutorial

It’s flavours and versions

Javascript, despite the name, is not part of the Java
programming language developed by Sun. It was originally introduced
with Netscape Navigator v2.0 and was designed to create dynamic online
pages, such as checking details on html forms before allowing the page
to submit the data.

Microsoft introduced their own scripting language –
related to Visual Basic and called VBScript – but since the release of
Internet Explorer v4 has fully supported Javascript in preference to
VBScript. Because of this rivalry, Microsoft Internet Explorer v3 is
NOT fully Javascript compatible and has numerous bugs and errors in the
way it interprets Javascript. You would be well advised not to use
Javascript in IE3 unless you have a way of testing all pages on both
IE3 and IE4 as well as Netscape. To achieve this, you will need to
identify the browser being used

Which browser, which version of Javascript?

IE3 is decreasing in usage and most internet visitors
using IE will use a more recent version. Other browsers like Konqueror,
Opera and Galeon also have Javascript abilities. However, Javascript
cannot be assumed to work in other browsers and may be disabled by the
user. IE3 may still be in use on local intranets and there are other
visitors who need to use text-only, voice-controlled or other browsers
that cannot support any kind of scripting. Your use of Javascript
should take into account your target audience by including <noscript> sections. Javascript is useful but it cannot replace a server-side script using PHP, Perl, Java or ASP.

Javascript also has security implications, for the user
and the data. In particular, e-commerce relying on Javascript can be
unreliable because of browser incompatibilities and all data handled by
Javascript code is fully visible to the user. This could include
sensitive data about your site. Javascript embedded in HTML format
emails poses security implications for users with the result is that
many users are advised to disable Javascript and VBScript. Without a
secure connection (using https://), the data is also available to anyone in between the user and the site.

Structure and syntax

Case Sensitivity
All keywords like var or function
must be in lowercase. All variable names, function names and
identifiers are case sensitive. The following two variables are
separate and independent of each other:

var Test = 6;
var test=4;

This code will cause a Javascript error:

function Test() {alert("Testing");}
function show_alert() {tesT();}

Whitespace
Like most programming and scripting languages, Javascript requires one
space between keywords, names and identifiers. Extra spaces are ignored
so you can use tabs and spaces wherever you need to make your code
easier to read and debug.

Semi-colons
Every line of Javascript must end in a semi-colon ;
Blank lines don’t need sem-colons.

Comments
You can use C and C++ style comments:

// this is a single line comment
/* this is a
multi-line comment */

Javascript code in HTML pages should be contained within HTML comment tags:

<script language="Javascript" type="text/javascript">
<!--
// Javascript here
// -->
</script>

Identifiers
(Variable names, function names, labels.)
The first character in an identifier name must not be a digit.
Javascript 1.0 does not allow identifiers to contain the $ character.
The following are not legal identifier names:

var $value;
function 1way() {};
Javascript Keywords
break for this
case function true
continue if typeof
default import var
delete in void
do new while
else null with
export return
false switch
Reserved for future use
catch finally
class super
const throw
debugger try
enum
extends

Variables
Declare variables using the keyword var. Javascript variables have no explicit data type and can contain data of any type.

var mynumber;
var mystring;
var myboolean;

Data types and objects

Data Types
Javascript can handle basic data types like numbers (all treated as
64-bit floating point values), boolean values (true or false) and
strings. Complex or compound data types can also be handled as objects
or arrays. Objects are not C++/Java classes, they act as associative
arrays with arbitrary data values and arbitrary names. Javascript 1.2
added support for regular expressions as a specialised data type.

Numbers
Numbers in Javascript are all floating point values – whole numbers
(integers) are not a separate type. Very large or very small values use
an optional exponent syntax:


6.02e23

Hexadecimal or octal notation can be
used to refer to an integer value, but Javascript will convert to a
decimal floating point value:
Octal: 0377 = 255
Hexadecimal: 0xFF = 255
Number overflows will generate a special value that represents positive
or negative infinity. This code illustrates the return values:

<script language="Javascript" type="text/javascript">
<!--
var x = -1000;
var y = 1000;
var a = Math.pow(x,y);
alert(a);
-->
</script>


Test here

Number underflows will return a zero value. Illegal number operations
like the square root of negative one or division by zero will yield an
error, returning a special value
NaN. Use the global
isNaN(); to test for these values.

Booleans
Use the keywords true and false to set variables as boolean data type.
var bool = true;

Strings
Not all character sets are supported
by all browsers, although ECMA-262 requires Javascript to support the
full 16-bit Unicode set. If you need to use Unicode, check browser
compatibility before implementing the Javascript.
Special characters can be "escaped" to change the meaning of the character within the string.

Escape Represents:
\b Backspace
\f Form Feed
\n Newline
\r Carriage Return
\t Tab
\' Apostrophe or single quote
that does not terminate the string.
\" Double quote
that does not terminate the string.
\\ Single backslash character
\ddd Character with Latin-1 encoding
specified by three octal digits
\xdd Character with Latin-1 encoding
specified by two hexadecimal digits
\udddd Character with Unicode encoding
specified by four hexadecimal digits

Objects
An object can contain any number of properties of any type. Use the .
operator to access a named property of an object. (In the code above,
Math.pow() is used to access an object method.)
obj.x = 1;
obj.y = 2;

Object properties can be accessed using standard array notation:

obj["x"] = 1;
obj["y"] = 2;

Typically, you create an object that is a member of a class of existing
objects and have suitable properties (and methods) already defined.

var time_now = new Date();

Arrays
Javascript arrays are a form of object that uses numerical values for
property names – as the object is normally an associative array anyway,
this gives you a normal array, just like in C, PHP Java etc. To create
an array, just use numerical values for the property names:

a[0] = 1;
a[1] = a[0] *2;

Every array has a length property assigned by Javascript. The last element in array is array[array.length-1];
Initialise the array using a constructor:
var x = new Array();
var y = new Array(4,5,7,12);

Functions and operators

Functions
A function can be used as standalone code to make it easier to execute multiple lines of
Javascript code, e.g. in response to <a
href="javascript:my_func();">Execute</a>

In Javascript 1.2, functions can also be assigned to a Javascript object to create a method
for that object. Use the keyword
this to refer to the object for which the function is a method.


<script type="text/javascript">
<!--
function sum(x,y) {
return x + y;
}
var total = sum(4,7);
alert(total);
-->
</script>

Operators

Javascript Operators
Operator Operation: Syntax
= assignment x="one";
[] Access an array element array[<name|number>]
() Invoke a function or separate operations myfunc(<values>) x=(y*z)-4;
++ pre or post increment by one ++x or x++
-- pre or post decrement by one --x or x--
+ - addition, minus x-y+z
+=,-=,*= shorthand for assign and add etc. a+=x; same as: a=a+x;
! boolean false if (!var) {}
delete delete an object property delete object;
new create a new object new object;
typeof return type of operand typeof var;
void return undefined value var = void;
* / % multiply, divide, modulus c=((x*y)/z)%a;
+ string concatenation x="one"+" two";
<,<= less than, less than or equal if(x<="2"){}
>,>= greater than, greather than or equal if(x>="2"){}
==, != test for equality or inequality if(x=="1") {}
&& Logical AND if((x!="2")&&(y=="1")) {}
|| Logical OR if((x!="2")||(y=="1")) {}
? : Conditional, if ?then:else if(x=="2") ? {y=2;} : {y=3;}
. Access object property object.property

When using multiple operators, use () to make sure the calculation works as
you expect.
x=y-2*z; will actually execute as x=y-(2*z);. To calculate x as
y minus 2 all multiplied by z, use x=(y-2)*z;

JavaScript Statements A-F

Simple statements
Statements make up the backbone of a Javascript program. Each time a
variable is created, changed, deleted, or output, each time a function
is declared, called or assigned, a statement is created. The following
are all examples of simple statements:
var s;
s="Hello, World!";
x=Math.sqrt(4);
y++;

Compound statements
To execute a series of statements as one, use {} brackets. Function declarations,
while and for loops and if and
switch conditionals all use {} brackets.


y=4; // simple statement
if (x==2) {
// conditional compound statement
y+=x;
c=Math.random();
y*=c;
}

break
Break from executing the current loop, if more than one, break stops
execution of the innermost loop, handing control back to the next
innermost. This example code never allows the value of x to exceed 8,
despite the loop being able to run to 14.

x=0;
while (x<=14) {
     if (x==8) {break;}
     x++;
}

case
Case is a keyword used to label compound statements within a switch statement.

switch (x) {
case 1 : {y=x;break;}
case 2 : {y=x;}
case 3 :
case 4 : {y=x;break;}
default : {y=0;break;}
}

Note that if x equals 2 or 3, the switch statement continues execution on to the
case 4 :
statement where the break statement stops further execution.

continue
Continue is used to restart the innermost loop.

x=1;y=1;
while (x<10) {
y++;
if (y==3) break;
else continue;
x++;
}

In this example, the x++ statement is never executed. At the
end of the loop, x remains equal to one and y is incremented to 3, at
which point the loop reaches break before the continue can be executed. Note that as x is never incremented, the loop must exit using break as the condition while (x<10) will never be met and the loop becomes infinite – your Javascript program will be terminated.

default
default is a keyword used in a switch statement usually as the last in
a series of case statements. The default case only executes if no case
statement matches the value of the expression in the switch statement.

do
Javascript 1.2 only
Use do to extend the function of the while loop. By default while doesn’t execute any code within the loop unless the while condition evaluates to true. If you need the code to execute ONCE even if the while condition doesn’t (yet) evaluate to true, use do to enclose the code:

x=1;y=1;
do {
     y++;
     if (y==3) break;
     else continue;
     x++;
}
while (x<10);

for
Simple loops can use for to save code by initialising, testing and
incrementing the test conditions in one statement:

for (initialise ; test ; increment) {}

for (x=0;x<10;x++) {}
The loop executes repeatedly until the test condition evaluates to
true. Initialisation code is executed once before the first evaluation
of the test or the loop. The test condition is evaluated before each
loop is executed and the increment expression is executed only once the
loop has completed (i.e. just before the next test condition
evaluation).

function
Functions are a way of executing compound statements in one HTML or
Javascript call with the extra flexibility of passing variables to the
function.

function my_func(x,y,z) {
     a=x+y-z;
     alert(a);
}

This function can be called from HTML as:
<a href="javascript:my_func(10,2,3);">Test</a>
Test
In this example, the alert box should show the result as 9.

JavaScript Statements G-Z

if and else
Use if
when a simple or compound statement must only be executed if certain
variables are already set to compatible values. The simplest if statement may be a test for division by zero:
a=4;
if (x!=0) {y=a/x;}

else
Use else to catch instances where the preceding if test condition failed. else cannot be used except immediately after the closing } of a valid if statement. In situations where if statements are nested inside other if statements, the else statement will apply to the if statement immediately preceding. Take care to put your else statements beneath the correct } bracket.
a=4;
if (x!=0) {y=a/x;}

else { alert( "Division by zero attempted!" ); }

return
Use return to stop execution of the current function and return control to the calling function/procedure.

function my_func(x,y) {
     return (x+y);
}

var sum = my_func(4,8);

The code has been adapted to run from HTML here
In this example, the alert box should show the result as 12.

var
Each variable in a function must be declared using var and optionally, var can be used to initialise the variable. Variables defined outside functions can be declared without var.


x=0;
function my_func(x) {
     var y=4;
     x+=y;
}

while
Simple loops can use while when the variable is already initialised but the contents of the while loop MUST increment or update the variable(s) in the test condition.


var x=0;
while (x<10) {x++;}

The loop executes repeatedly until the test condition evaluates to
false. The test condition is evaluated before each loop is executed.
Note the difference between for and while test conditions, for loops execute until the test condition is true. while loops execute until the test condition is false.

JavaScript Events

Javascript: Events
Parent element child elements inherit:
Input Button Methods, Properties and Event Handlers
Checkbox
FileUpload
Password
Radio
Reset
Select
Submit
Text
Textarea
HTMLElement All Input children Methods, Properties and Event Handlers
Plus: Anchor
Document
Form
Image
Input
Link
Option
Input Hidden Methods and Properties only

In the following table, if all the child elements inherit all the event
handlers, only the parent elements from the table above are given.

Handlers for Javascript elements
Handler Element Version
onAbort() Image 1.1
onBlur() Window, Input 1.1
onChange() Input  
onClick() Button, Link. Return false to cancel default action. 1.2
HTMLElement
onError() Image, Windows 1.1
onKeyDown() Document, Image, Link, Password, Text, Textarea. Return false to cancel default. 1.2
onKeyPress() Document, Image, Link, Password, Text, Textarea. Return false to cancel default. 1.2
onKeyUp() Document, Image, Link, Password, Text, Textarea. Return false to cancel default. 1.2
onLoad() Window 1.1
Image
onUnload() Window 1.1
Image
onMouseDown() Document, Link, Image, Button. Return false to cancel default action. 1.2
onMouseUp() Document, Link, Image, Button. Return false to cancel default action. 1.2
onMouseOver() Link: Return true to prevent URL display. 1.2
Image, Layer. Return true to prevent URL display.
onMouseOut() Link: Return true to prevent URL display. 1.2
Image, Layer. Return true to prevent URL display.
onReset() Forms: Return false to prevent reset 1.1
onSubmit() Forms: Return false to prevent form submission 1.1

JavaScript Global Properties

Infinity
A numeric constant that represents infinity.
(Covered by ECMA-262 but not supported by Navigator v4.)

NaN
A constant to indicate that a variable value is not a number. Use to
prevent unpredictable results when such values are used in a numerical
calculation. (Covered by ECMA-262 but not supported by Navigator v4.)

Global Functions

escape(string)
Encode a string for transmission.

eval(code)
Execute Javascript code from a string

getClass(javaObject)
Return the JavaClass of a JavaObject.

isFinite(number)
Check if a numerical value is finite.

isNaN
Check for the Not a Number value.

parseFloat(string)
Convert a string to a number.
(Check for NaN first.)

unescape(string)
Decode an escaped string.

Javascript code to identify your browser

Note: Using this code will mean your page would
have to be validated as HTML4 Transitional because the language=""
attribute is not part of HTML4 and will cause validation of a HTML4
Strict file to fail. The need for this type of code is diminishing with
the increasing support for CSS1 and CSS2.

Each browser identifies itself by means of a navigator
object. This object is accessible through all versions of Javascript.
To use the identity of the browser to redirect the user to the
appropriate page, we need to store the identity of the browser as a
variable:

<script type="text/javascript">
var isNew=0;
var isNS4=0;
var isIE4=0;
var isIE5=0;
var isNS3=0;
var isIE3=0;
// -->
</script>

These variables need to be accessed by all browsers.
However, each browser can only access javascript up to the version it
can understand, therefore early browsers will ignore all javascript
code marked as of a later version – even if the code itself is an
earlier version. So if you need to exclude IE3, Netscape 2 and Netscape
3 from the next section of code, specify Javascript1.2 (note, that the
language attribute is no longer part of HTML4 – validate as HTML4
Transitional if you need to use this to exclude certain browsers in
this way.)

<script language="Javascript1.2" type="text/javascript">

Now we address the navigator object and ask for the
name of the browser. The same line of code looks for a version number
in the navigator.appVersion data and appends that to the browser name

var brow=((navigator.appName) +
(parseInt(navigator.appVersion)));

Now we test for which browser is in use and store the result.

if(parseInt(navigator.appVersion >=5)) {
if(brow == "Microsoft Internet Explorer5") isIE5=1;
else isNew=1;
}
else if(brow == "Netscape4") {isNS4 = 1;}
else if(brow == "Microsoft Internet Explorer4") {isIE4=1;}

Netscape 3 has not yet been identified, so we specify Javascript1.1 to
exclude IE3 and Netscape 2.

<script language="Javascript1.1" type="text/javascript">

Finally, it’s back to Javascript (version 1 as it’s not
specified) to find IE3. Work on this code yourself, but note that there
is a bug in IE3 – it reports the name as Microsoft Internet Explorer
but reports the version as Mozilla 2. Therefore, the code used above
will return

brow="Microsoft Internet Explorer2".

Redirecting the browser once identified

The Window object and how to change the location

<script type="text/javascript">
<!--
if (isIE3) {window.location.href="IE3_PAGE";}
else if (isNS3==1) {window.location.href="NETSCAPE3_PAGE";}
else if (isNS4) {window.location.href="NETSCAPE4_PAGE";}
else if (isIE4==1 || isIE5==1 || isNew==1)
{window.location.href="NEWEST_PAGE";}
// -->
</script>

Remember to substitute IE3_PAGE, NETSCAPE3_PAGE etc for the URL of the
correct page on your site.

Window is a global object in all browsers (can be
addressed from any Javascript) and the location property contains the
href just the same as a link (<a href=) contains a href property.
Changing window.location.href using Javascript causes the browser to
move to the new location.

The rest of the code is not executed once the location
has been changed. So each browser leaves the code at a different point,
IE3 first, NS3 second, etc.

2010-05-25T22:52:44+00:00 November 9th, 2007|JavaScript|0 Comments

About the Author:

Leave A Comment