Introduction To Computational Media on the Web (ICM-W) : Week 2
JavaScript Introduction
JavaScript is a scripting language that is typically used on web pages and runs client-side (within the web browser, not on the server). It is a general purpose language but it excels at interacting with elements available on the page in HTML and responding to actions initiated by the user.
Although the JavaScript has "Java" in it's name, it isn't related other than by the fact that it looks something like Java. JavaScript's official name is ECMAScript (ECMA is the European Computer Manufacturers Association and is a standards body). It was created by Netscape Communications.
Comments in JavaScript have to be done differently than in HTML:
<script type="text/javascript">
// Single Line Comment
/*
Multiple
Line
Comment
*/
</script>
Variables
Variables are containers for data. Essentially a variable is something that can hold a value and that value can be changed (They can vary).
Data Types
Variables in JavaScript (and many other scripting languages) are loosely typed and do not need to be "declared" with their type.
Other languages such as Java are strictly typed and each variable must declare the type of the data it will contain.
Regardless of whether or not JavaScript is loosely or strictly typed we still need to be aware of the types of variables that JavaScript understands:
Number - A number with a decimal point. In other languages this is typically called a float. var anumber = 5; or var anothernumber = 1.223;
String - A series of characters. These can be defined with either single or double quotes. var astring = 'Hello'; or var anotherstring = "Til tomorrow";
Boolean - A "True" or "False" value. var aboolean = false; or var anotherboolean = true;
For comparison, this is the set of data types available in Java (and many other languages):
integer - A whole numbers. int someint = 5;
boolean - True or False. Often the result of an expression. boolean somebool = true;
float - A number with a decimal point. 1.5, 3.987 and so on. float somefloat = 99.76;
byte - An 8 bit value. Ranges from -127 to 128 in value. byte mybyte = -90;
char - A single character. char mychar = 'A';
(You notice that in Java you include the "type" when declaring the variable.)
Assignment
Once they are declared, you are free to assign values to them and subsequently use them in operations:
var myinteger = 5;
myinteger = 5 + 5;
myinteger = myinteger - 5;
var yourfloat = 5.5;
An example:
<script type="text/javascript">
var avariable = 0; // Assigns 0 to be held by a variable named "avariable". The name can be anything you want it to be.
avariable = "something else"; // Changes what "avariable" holds by assigning it to be "something else". Also switches it's type. Don't need to use "var" again as avariable is already declared.
alert(avariable); // This is a function which we can use to display something in a pop-up alert box. We'll get to functions more next week but this is one we need for now.
</script>
alert is a built-in function that generates an alert box containing whatever you put in the parenthesis. Technically it is window.alert but with function that references "window" we don't need to include "window.". We'll cover this more as we get into Functions and Objects.
Relational Operators:
>= (greater than or equal to)
<= (less than or equal to)
== (equality)
!= (inequality)
=== (equality with type checking)
!== (inequality with type checking)
Truth tables:
Logical operators follow the following rules when evaluating to "true" or "false".
Or
True
False
True
true
true
False
true
false
And
True
False
True
true
false
False
false
false
Conditionals
Execute a block of code based on the result of an expresssion that utilizes relational or logical (boolean) operators
If Statement:
var anint = 1;
if (anint >= 0)
{
// Execute some code
}
If Else Statement:
var anint = 1;
if (anint >= 0)
{
// Excute some code
}
else
{
// Execute some other code
}
If, Else If, Else:
var anint = 1;
if (anint >= 0)
{
// Execute some code
}
else if (anint < -1)
{
// Execute some other code
}
else
{
// Execute this code if none of the other conditions are true
}
You can use the boolean operations to use boolean logic on multiple expressions.
var anint = 1;
var anotherint = 2;
if (anint > 0 && anotherint <= 2)
{
// Execute some code
}
Indentation:
Notice above how I indent code that is within the blocks (within "{ }"). This is purely for readability and understanding. Do it, you will thank me later.
Loops
While:
Just as with our conditional (if / else) statements a while loop employs boolean test that must evaluate to true in order for the instructions enclosed in the curly brackets to be executed. The difference is that the instructions continue to be executed until the test condition becomes false.
var x = 0;
while (x < 10)
{
document.writeln(x + " is less than 10.<br />");
x++;
}
For Loop
Since this is a common use of a loop (creating a variable, checking it's value and incrementing by a certain amount) there exists an even quicker way to do the above, all in one step.
for (var x = 0; x < 10; x++)
{
document.writeln(x + " is less than 10.<br />");
}
You can read this as, create variable x and set it to 0, while x is less than 10, do the following. Increment x by 1 at the end.
Exactly what we are doing in the while loop but in one quick step.
Printing Text Output to HTML
document.write() and document.writeln():
These built-in functions allow you to print text to the body of the HTML document as if the text was HTML. They are perfect commands for debugging and learning the value of a variable. Use them like you would use comments.
document.writeln(mybyte); Prints out the value of mybyte.
document.writeln(somefloat); Prints out the value of somefloat
document.writeln("The value of somefloat is: " + somefloat); Concatinates the string specified in "" with the value of somefloat
Functions
We'll explore functions in more depth but for now let's just cover the basics.
A function is a reusable chunk of code. It is a way to encapsulate a set of instructions so you can run them when you want or run them over and over again.
You define a function in JavaScript like this:
function aFunctionName()
{
// Some code to execute
}
Always begin with the word "function" and then name it. The parenthesis allow you to take in "arguments" that are variables that can be used within the function.
A very simple function:
function writeAndAlert(whattowrite)
{
alert(whattowrite);
document.writeln(whattowrite);
}
You can call this function anywhere in your code (after you have defined it):
Variables that you declare inside a function (and in other languages inside any block of code) are local to that function.
If I have a function called blah and inside blah I declare a variable called "counter", I can not refer to counter outside of the function. In the case that I want to use the value of counter outside of the function, I either have to declare it outside of the function or return it's value.
var aGlobalVariable = "Global";
function globalLocalTest()
{
var aLocalVariable = "Local";
alert("Inside Function Global: " + aGlobalVariable);
alert("Inside Function Local: " + aLocalVariable);
}
globalLocalTest();
alert("Outside Function Global: " + aGlobalVariable);
alert("Outside Function Local: " + aLocalVariable); // This may not even appear
Having a form available on a web page allows the page to take input from a user and send it to a server for processing. It also allows the page to be responsive or interactive by using JavaScript to respond to form related data or events.
Putting a form on a page is as simple as using the various form tags nested within a set of <form> tags.
<form>
</form>
Form tags:
Text Field:
<input type="text" name="textfield" value="The Value" />
Allows text to be entered. The "value" attribute can be used to specify a default value.
Hidden Field:
<input type="hidden" name="hiddenfield" value="The Value" />
Allows a value to be in the form but not displayed to the user. The "value" attribute specifies the value.
Button:
<input type="button" name="pushbutton" value="Button" />
Button that can be pressed by the user. The "value" attribute is what displays on the page. Generally this is used to trigger an event that will call some JavaScript.
Submit:
<input type="submit" name="submitbutton" value="Submit" />
A button that is used to submit the form to the server. The "value" attribute is what display inside the button.
Reset:
<input type="reset" name="resetbutton" value="Reset" />
A button that is used to reset the form to the state it was when loaded. The "value" attribute is what display inside the button.
Radio Buttons:
Radio 1:
Radio 2:
<input type="radio" name="radiobutton" value="Radio 1" />
<input type="radio" name="radiobutton" value="Radio 2" />
A series of radio buttons that allow the user to choose between a series of options. Each one has the same "name" attribute but a different "value" attribute.
Select List:
<select name="selectlist">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
A drop down list of options that allows the user to select one. Multiple selections can be enabled by adding the keyword "multiple" in the "select" tag.
Form Actions
One of the nice things about forms in HTML is that you can execute JavaScript when information is selected or typed into the form. The means to do this is to use an additional attribute within the tag for the form element itself.
For instance, the "input" tag supports a whole slew of different events that can be specified by using an attribute:
HTML <input> Tag (look for Event Attributes).
Within these attributes you can specify JavaScript to be executed with the event occurs:
<input type="text" name="something" onkeypress="alert('you pressed a key');" />
Another reason to use the "id" attribute in your HTML tags besides for CSS is so that you can easily access the element from JavaScript.
The built-in function you use is called document.getElementById() and you pass in as an argument the ID (as a string so in ""). This function returns a reference to the element on the page so you can modify it. The easiest way to modify it is to use the "innerHTML" property attribute of a "div" element. We'll go over properties of objects more next week but this one is useful so I wanted to show it.
<html>
<head>
<title>
</title>
<script type="text/javascript">
function buttonPushed()
{
var theDiv = document.getElementById("thediv");
theDiv.innerHTML = "Other Content in the div now";
}
</script>
</head>
<body>
Some content..
<div id="thediv">
Content in the div
</div>
<form>
<input type="button" name="abutton" value="push me" onclick="buttonPushed();" />
</form>
</body>
</html>