JavaScript is a client side programming language designed to give life to the web. JavaScript is interpreted on the fly by the clients browser. Different browsers handle some elements of JavaScript differently, so sometimes, cross browser coding is necessary. Below, you will find a simple guide for programmers as an introduction to JavaScript. Those who have programmed in C++, Java or C# should have little difficulty in making the transition.

Basic Language Features
Variables and Output
Input
Conditions

JavaScript supports the use of if...else structures and switch statements. The logical operators used are &&(AND), ||(OR), and !(NOT). Also, the use of == is for comparison, while = is for assignment. if(condition){ ...true code... } else{ ...false code... } switch(variable){ case value: code; break; case value: code; break; default: code;

Iteration (skip for CS2)

JavaScript supports the use of for, while and do¡Kwhile structures. In addition, there exists a for each loop. The format for each of the loops are as follows: for(var x; x<value; x++{code} while(x<value){code} do{code}while(x<value); for(var x in array){code}

Methods
JavaScript allows the creation of functions. Without functions, JavaScript code will run automatically when encountered. JavaScript functions can take multiple parameters, but can only return one variable. The basic syntax for creating a function is: function functionName(parameter list){ code } JavaScript functions can be called from other JavaScript code, from the href attribute of an a tag, or using events.

Events

Events are actions, triggered by a user, that cause code to be executed. It is the ability to create and handle events that allows JavaScript to help make the web dynamic and interactive. Most often, an event is written as an attribute of an HTML tag and calls a JavaScript method. That method then uses JavaScript and the DOM to gather information and make changes to the page. Here is a list of some events and the HTML elements that they can be used on. This is not an exhaustive list, but a list of commonly used events and the elements that they are most often used on.
 onblur              when an element loses focus
 button, input, label, select, textare, body
 onchange  selection in an element loses focus and value changes when focus returns
 input, select, textarea
 onclick  mouse press and release
 most elements
 onfocus  element gains focus
 button, input, label, select, textarea, body
 onload  when the element completes loading
 body, img
 onmousedown  mouse button is pressed
 most elements
 onmousemove  mouse moves
 most elements
 onmouseout  mouse moves off element
 most elements
 onmouseover  mouse moves over element
 most elements
 onreset  form reset requests
 form
 onresize  window changes size
 body
 onselect  text selected
 input, textarea
 onsubmit  form submission requested
 form


Arrays (skip for CS2)

In JavaScript, an array is an object. So, variables that store arrays must be declared and instantiated var names=new Array();. While the typical array subscript notation is allowed, JavaScript also provides several methods for manipulating the array including pop(), push(), shift(), and unshift().

Standard Classes

As mentioned, JavaScript is an Object Oriented Programming Language. This means that users can create their own variable types and function libraries. JavaScript has provided many objects for use already, including:

JavaScript vs. Java


Below you will find a table comparing many of the basic commands/ideas from Java and JavaScript. This table will help JavaScript programmers see some basic differences between the two languages.
JavaScriptJava
Language Type Object Oriented / Interpreted Object Oriented / Compiled
Comments // & /*...*/ // & /*...*/
Console Output document.write() System.out.print()
System.out.println()
Dialog Output window.alert() JOptionPane.showMessageDialog();
Concatenation Operator + +
Variables var age = 43;
var gpa = 3.5;
var name = "Jim";
var isMale = true;
var middleInit = 'G';
int age = 43;
double gpa = 3.5;
String name = "Jim";
boolean isMale = true;
char middleInit = 'G';
Console Input name=document.getElementById('name');
age=parseInt(document.getElementById('age'));
gpa=parseFloat(document.getElementById('gpa'));
name=reader.nextLine();
age=reader.nextInt();
gpa=reader.nextDouble();
Dialog Input name=window.prompt("Enter Name");
age=parseInt(window.prompt("Enter age"));
gpa=parseFloat(window.prompt("Enter GPA"));
name=JOptionPane.showInputDialog("Enter Name");
age=Integer.parseInt(JOptionPane.showInputDialog("Enter Age"));
gpa=Double.parseDouble(JOptionPane.showInputDialog("Enter GPA"));
Math Methods Math.sqrt(num);
Math.pow(base,exp);
Math.min(num1, num2, ...);
Math.max(num1, num2, ...);
Math.round(num);
Math.ceil(num);
Math.floor(num);
Math.abs(num);
Math.random();
Math.PI;
Math.sqrt(num);
Math.pow(base,exp);
Math.min(num1, num2);
Math.max(num1, num2);
Math.round(num);
Math.ceil(num);
Math.floor(num);
Math.abs(num);
Math.random();
Math.PI;
String Methods str.length;
str.indexOf(string);
str.lastIndexOf(string);
str.charAt(num);
str.toUpperCase();
str.toLowerCase();
str.substring(start, [end]);
str.substr(start, length);
str.length;
str.indexOf(string);
str.lastIndexOf(string);
str.charAt(num);
str.toUpperCase();
str.toLowerCase();
str.substring(start, [end]);
str.equals(string);
str.equalsIgnoreCase();
str.compareTo(string);
str.compareToIgnoreCase(string);
Conditions if(condition)
code
else
code
if(condition)
code
else
code
For Loop for(var x=0; x<5; x++) for(int x=0; x<5; x++)
While Loop while(condition) while(condition)
do...while do{...}while(condition); do{...}while(condition);
Functions function funcName (age, gpa){
code;
return value;}
public static int funcName(int age, double gpa){
code;
return value;}
Arrays var arr=[];
arr[0]=53;
int [] arr=new int[10];
arr[0]=53;


The JavaScript DOM

Problems of the Past

In the early days of the world wide web, Netscape and Microsoft recognized the need for creating layers that could be altered while the page was being viewed. However, as is often the case, the companies implemented this concept differently forcing designers to ‘browser sniff’ and create multiple versions of their sites to be compatible with each browser. In recent years, the W3C has been working to create a set of commands that allow programmers to design interactive pages that are cross-browser compatible without the need for browser sniffing.

The W3C and the DOM

Starting with Netscape Navigator 6 and Internet Explorer 5, both browser companies have become compliant with a standard way of accessing elements in a web page. This implementation was designed by the W3C and is based on the basic structure of the page. This structure is called the DOM, Document Object Model, and is a tree representation of an HTML document.The tree structure is based on parents, children and siblings. This allows javascript to enter, access and modify an HTML document on the fly. Look at the following HTML code and the "tree" view that Javascript forms.

In the DOM, each element on the tree is called a node. These nodes take on a family style relationship. A node above an element on the same path of the tree is called a parent. Nodes below an element on the same path are called children. To elements at the same level with the same parent are called siblings.

The parent of all elements is the html tag. Its children are the header and the body. Since they are at the same level, the head and body tags are called siblings. They each have a child: title is the child of head and p is the child of body. And, each of those children have children. By navigating our way through the dom, we can alter text, style properties, and add, deleter or modify nodes.

Working with the DOM

The most common way to enter the DOM is using an element's id attribute and the document object. The element is returned as an object though the var elem=document.getElementById('id');. Once we have the element object, we can use a variety of methods to alter it attributes and contents. The easiest way to do alter the content of the object is to use .innerHTML(). The innerHTML method takes a single parameter of the string type that can contain both text and html and replaces all html within the opening and closing tags. Attributes of the desired element can be altered using the setAttribute() method. The setAttribute method takes two string parameters, the first being the attribute and the second being the value. Finally, styles can be changed in the DOM using the .style.property='value' property. So, in an example of the above, if we wanted to alter the size and color of a div with id 'myDiv', we would do the following: <div id='myDiv' onclick='change()'><div> <script> function change(){ var div=document.getElementById('myDiv'); div.setAttribute('width', '100px'); //sets the width of the div to 100px div.style.backgroundColor='blue'; //changes the background color to blue div.innerHTML('<em>Italic text</em>'); //add the words Italic text (in italics) to the inside of the div } </script>