Introduction to Javascript


Static versus dynamic web pages


Basic HTML allows us to prepare the appearance of a static web page. if we want to display dynamic data, or want the layout and content of the page to respond to user events dynamically, then additional features are needed in the web page more than basic HTML

Approaches to provide this include :


All of these break down into two types: 1) Server-side and 2) Client-side programs. The server-side programs run on the web server and the results of the programming running are sent to your browser on your local machine. Client side programs are sent to your machine by the web server and run on your local machine.

Server side programs require the input to be transmitted from the client to the server and then the output or results transmitted back to the client. This increases network traffic. The server also has to do the calculations - thus increasing the load on the server.

Client-side programs eliminate this - the program is sent to the client and then all the work and data input and output is done on the client.

Client-side pros and cons


Server-side pros and cons



Development of Java and Javascript - Note Javascript is not Java.


JavaScript - Strengths


JavaScript - Weaknesses

JavaScript and HTML

HTML tags <SCRIPT> , </SCRIPT> contain the JavaScript portion within the HTML document
<SCRIPT LANGUAGE="JavaScript">
JavaScript program goes here
</SCRIPT>
Hiding scripts from browsers that do not support JavaScript
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide the Script from other browsers
JavaScript program

// Stop hiding from other browsers -->

</SCRIPT>

Where to place the JavaScript code ?

JavaScript programs can be included anywhere in the header or body of an HTML file but the preferred location is in the header just after the </TITLE> tag. Long and complex scripts can be placed in a separate file (must have a .js file extension) - Some browsers support this.  Test it.

<SCRIPT LANGUAGE="JavaScript" SRC="http://www.you.com/JavaScript.js">



Example:

<HTML>
<head>
<TITLE>JavaScript Sample </TITLE>
</HEAD>
<BODY>
Here's a sample JavaScript:
<SCRIPT LANGUAGE="JavaScript">
  <!-- Hide from other browsers
  // Display a message
  document.writeln("Have a nice day!<BR>");
  // Stop hiding from other browsers -->
  </SCRIPT>
</BODY></HTML>

Javascript language syntax.

document.write("Welcome !");

document.writeln("Have a great day!");

The "write" sends the text on the current line in the browser. The "writeln" sends the text on a new line in the browser. The SCRIPT container does not affect the HTML structures where it occurs, so any format tags or elements in the HTML file will affect the text produced by write()

<HTML><HEAD>
<TITLE>JavaScript Sample </TITLE>
</HEAD>

<BODY>
Here's a sample JavaScript <B>
<SCRIPT LANGUAGE="JavaScript">
  <!-- Hide from other browsers
  // Display a message
  document.writeln("This is in bold.</B>");
  // Stop hiding from other browsers -->
</SCRIPT>
</BODY></HTML>


Interacting with the user

The simplest way is with the prompt() method. Prompt displays the first argument as the prompt text, the second argument is displayed as the default value within the dialog box.


<SCRIPT LANGUAGE="JavaScript">
<!-- Hide from other browsers

document.write('<IMG SRC="welcome.gif">');
document.write("<H1>Greetings, ");
document.write(prompt("Enter your name:", "Name"));
document.write(". Welcome to Netscape! </H1>");

// Stop hiding from other browsers -->
</SCRIPT>

The prompt method doesn't need to be prefixed by document because it is part of the window object. If the object name is missing, then window object is assumed.

alert dialog box

Is useful to show some information in a dialog box

alert("Click OK to continue.");

useful to point out incorrect information in a form or invalid result from a calculation, other messages


<SCRIPT LANGUAGE="JavaScript">
<!-- Hide from other browsers

document.write('<IMG SRC="welcome.gif">');
alert("Welcome to my page !");
document.write("<H1>Greetings, ");
document.write(prompt("Enter your name:", "Name"));
document.write(". Welcome to Netscape! </H1>");


// Stop hiding from other browsers -->

</SCRIPT>

JavaScript Data Types


JavaScript provides four basic data types

  1. Numbers as in 21 and 32.62 - integers and floating point numbers
  2. Strings as in "Hello" and "There" - strings must be enclosed with a pair of single or double quotation marks
  3. Boolean either true or false
  4. Null special keyword for a nothing value - when you create a variable and haven't assigned a value to it yet

JavaScript Casting

JavaScript is a loosely typed programming language
use parseInt() and parseFloat() functions to convert strings to integers or floats.

JavaScript - Variables

Variables in JavaScript can be of any data type

<SCRIPT LANGUAGE="JavaScript">
  <!-- Hide from other browsers

  var name=prompt("Enter your name:", "Name");
  document.write('<IMG SRC="welcome.gif">');
  document.write("<H1> Greetings, " + name + ". Welcome to my page! </H1>");
  // Stop hiding from other browsers -->
</SCRIPT>


The following assignment statements are equivalent:

var example;
example = "Here is an example";

var example = "Here is an example";

Variable names are case sensitive and must start with a letter or an underscore

JavaScript  Expressions


Assignment which assigns a value to a variable


Arithmetic evaluates to a number

Reset x and y to 10 and 5
String evaluates to a string

A = "Today" + " is Friday";     // A is "Today is Friday"

Logical evaluates to a boolean value

comparison operators


x = 10;
y = 5;
( x < y ) && ( x == 5 )    // is false
( x > y ) || ( x < 5 )     // is true


JavaScript Conditional

as in C, C++

(condition) ? value1 : value2;

if (condition) evaluates to true, then value1 is returned; otherwise, value2 is returned


JavaScript  String

concatenation operator is +

"Welcome to " + "my site!" becomes "Welcome to my site!"

welcome += " Thank-you." adds the string "Thank-you." to the end of the string variable called welcome.


JavaScript - if construct


Syntax:

if (condition is true) {
  Javascript commands if true
} else {
  Javascript commands if false
}


if ( day == "Saturday") {
  document.writeln("It's the weekend!");
} else {
  document.writeln("It's not Saturday.");
}


JavaScript - Confirm


The confirm method allows the user to select an OK button or a Cancel button.  Confirm returns true if OK is clicked, false if Cancel is clicked.


if (confirm("Press OK to retry.")) {
  response = prompt("What is 2+2", "3");
}



An example using confirm:

<HTML><HEAD><TITLE>An Example</TITLE>
<SCRIPT LANGUAGE="JavaScript">
  <!-- hide from older browsers
  // define some variables

  var question = "What is 10+10?";
  var answer = 20;
  var correct = '<IMG SRC="correct.gif">';
  var incorrect ='<IMG SRC="incorrect.gif">';
 
  // ask the question
  var response = prompt(question,"0");

  // check the answer

  if (response != answer) {
  // wrong answer; retry once
    if (confirm("Wrong! Press OK for a second chance."))
      response = prompt(question,"0");
  }

  // check the answer

  var output = (response == answer) ? correct : incorrect;

  // stop hiding from older browsers -->

</SCRIPT>
</HEAD>

<BODY>

<SCRIPT LANGUAGE="JavaScript">

  <!-- hide from older browsers
  document.write(output);
  // stop hiding from older browsers -->

</SCRIPT>
</BODY></HTML>

JavaScript - Functions - creating.

Defined using the function statement


function function_name( parameters, arguments) {
  command block

}

For example:

function printName( name ) {
   document.write("<HR>Your Name is <B><I>");
   document.write( name );
  document.write("</B></I><HR>");
}


functions should be defined in the header. This ensures that all functions have been parsed before it is possible for user events to invoke a function


eval() method

evaluates a string to a numeric

e.g. eval("4 + 5") returns a value of 9


Examples


<SCRIPT LANGUAGE="JavaScript">
   <!-- hide from older browsers
   // define function testQuestion()
   function testQuestion(question) {
     // define some local variables
      var answer = eval(question);
      var output = "What is " + question + "?";
      var correct = '<IMG SRC="correct.gif">';
      var incorrect = '<IMG SRC="incorrect.gif">';
      // ask the question
      var response=prompt(output,"0");
      // check the result
      return (response == answer) ? correct : incorrect;
   }

  // stop hiding from older browsers -->
  </SCRIPT>

</HEAD>
<BODY>

<SCRIPT LANGUAGE="JavaScript">
   <!-- hide from older browsers
   var result = testQuestion("4 + 5");
   document.write(result);
   // stop hiding from older browsers -->
</SCRIPT>

JavaScript - Dates

variable = new Date( parameters )

if no parameters are supplied, then the current date is used.



a Date object, like other objects, has methods associated with it

Methods must be applied to objects using the format of object_name.method_name() as in



example:


<HEAD><TITLE>Day Test using Javascript</TITLE>

<SCRIPT LANGUAGE="JAVASCRIPT">
  <!--Hide from non-JavaScript browsers
  // This function calculates the number of days until Christmas

  function XmasDays(Month, Day, Year) {

    var DayCount = (25-Day) + 30;
    return DayCount;
  }

  // Stop hiding -->

</SCRIPT>
</HEAD>

<BODY>
<SCRIPT LANGUAGE="JavaScript">
  <!--Hide from non-JavaScript browsers
  // Get date information
  var Today = new Date("November 1, 1998");
  var ThisDay = Today.getDate();
  var ThisMonth = Today.getMonth() + 1;
  var ThisYear = Today.getYear();
 
  document.write("Today is "+ThisMonth+"/"+ThisDay+"/"+
  ThisYear+"<BR>");

  // Get number of days until Christmas
  var DaysLeft = XmasDays(ThisMonth, ThisDay, ThisYear);
  document.write("Only " + DaysLeft + " days until Christmas");
  // Stop hiding -->
</SCRIPT>


Arrays in JavaScript

An array is an ordered collection of values referenced by a single variable name.

  1. Weekday[1]="Monday";
  2. Weekday[2]="Tuesday";
  3. Weekday[3]="Wednesday";
  4. Weekday[4]="Thursday";
  5. Weekday[5]="Friday";
  6. Weekday[6]="Saturday";
  7. Weekday[7]="Sunday";
Each element is identified by an index, the number appearing in the brackets. For example, the element "Monday" has an index of 1. In the Weekday array there are actually eight elements in total. The first element is Weekday[0], and it has the null value.


The syntax for creating an array variable is

var variable = new Array( size );

specifying the size is optional. Javascript will automatically increase the size of the array as you add more elements.


var Month = new Array();
Month[12] = "December";

Javascript will create 13 elements for the Month array all having null values except for the Month[12] element.

Looping


A loop is a set of instructions that is run repeatedly. There are two kinds of loops: a loop that repeats a set number of times, and a loop that will continually repeat until a condition is met.


The For loop is the first kind


Syntax:

for (start; stop; update) {

  Javascript commands

}



// this will repeat exactly three times
for (Num=1; Num<4; Num++) {

  document.write("The value of Num is " + Num + "<BR>");

}



The While loop is the second kind

Syntax:

while ( condition is true ) {

  Javascript commands

}

// repeats three times
var Num = 1;

while (Num < 4) {
  document.write("The value of Num is " + Num);
  Num++;
}

JavaScript Resources