Using JavaScript

Download Report

Transcript Using JavaScript

Just Enough JavaScript
Javascript code is triggered by “events”
Document Events
onload, onunload
Mouse Events
onclick, ondblclick
onmousedown, onmouseup
onmousemove, onmouseover,
onmouseout
Key Events
onkeypress, onkeydown, onkeyup
Form Events
onfocus, onblur, onselect, onchange
onsubmit, onreset
New events proposed Jan 2010 in HTML5
In many ways JavaScript is just like
but it’s not really like
Common Programming Language Features
•
•
•
•
•
•
•
•
•
•
Comments
Data Types
Variable Declarations
Expressions
Flow of Control Statements
Functions and Subroutines
Macros and Preprocessor Commands
I/O Statements
Libraries
External Tools (Compiler, debugger etc)
Comments
//Single line comments
/* Multiple line
comments */
The Simplest Program
<!- - HTML Comment: - ->
<script>
//This shows a simple message box
alert(‘Msg’);
</script
JavaScript inserted into HTML
<body>
<script type="text/javascript">
alert('Opening Page');
function myMsg(s){ alert('msg: '+s); }
alert('After this the page is displayed');
</script>
<input type=button value=‘Click Test’
onclick=“alert(‘alert1’);
myAlert(‘alert2’);” />
</body>
•Javascript outside of a function and inside <script> tags runs when the web page is loaded
•JavaScript code and calls to JavaScript functions can be triggered using events such as onclick
•When quoting strings use either single quote or double quote – be consistant
Refering to an external file of functions
<script type="text/javascript"
language="javascript" src="hello.js">
Built In Dialogs
• alert(msg); //simple message box
• confirm(msg); //shows yes/no. returns
true/false
• prompt(msg,default value); //input box
IE supports additional dialog boxes – avoid!
document.execCommand(‘SaveAs’);
getElementByID(‘idvalue’)
<button onclick='javascript:
result=prompt("Enter your name","Default");
display=document.getElementById("disp");
display.innerHTML=result;'>
<tag id=disp>Result will show here</tag>
Note the purpose of these 3
attributes!
<tag id=‘uniqueName’
name=‘groupName’
class=‘styleName’ />
id: a unique identifier in your page
name: used for radio buttons and name/value
pairs passed in query strings
class: used to link a particular style with a tag
Data Types
•
•
•
•
Number
String
Boolean
Date
There are 2 other “special” types
• Undefined
• Null
Variable Declarations
• var counter,
pi=3.15159265,
name=‘Fred’,
name2=“Janna”,
completed=true,
approved=false;
•
•
•
•
Javascript is a weakly typed language
We don’t have to declare a data type
The type of a variable depends on what we assign to it
The data type can change at any time.
Variables names are case sensitive. (So are JavaScript
keywords like var)
Declaring Arrays
• var names=[‘Mary’,”Murray”,”Jim”];
var nestedArray=[ [1,2,3], [4,5,6], [7,8,9]];
var list=new Array(‘Martha’,’Muffin’,’Donut’,18);
var myArray=new Array();
for(i=1;i<10;i++) myArray[i]=i*i;
myArray[100] = 42;
We don’t have to say how big an array is in advance of its use!
We can mix different data types in an array!
Declaring Variables
To indicate a constant: ALL_CAPS
ie: var GRAVITATIONAL_CONST=6.67300 e-11;
variables use camelCaps
var firstName=‘George’;
datatypes use camel caps that start with a capital:
class NetworkCard ....
Scope
var msg="I am a global variable";
var counter=1; //also gobal
function display(msg) //This msg is local
{
var local;
alert(msg+local+counter);
counter++;
}
display("Local value of msg");
display(msg); //Use global value and insert into function
Hungarian Notation
The practice of putting a prefix
to indicate the datatype of a
variable, named after Charles
Simonyi
sFirstName - its a string
bFound its a boolean
asNames - array of strings
dBirth
- date
It’s encouraged in Microsoft communities
Operators
Standard C arithmetic operators will work
++
-* / %
+ += -= *= /= %=
? : (triadic operator)
The + operator also concatenates Strings:
5+5 becomes 10, ‘5’+’5’ becomes ‘55’ - this could create problems
result=‘Hello ’+’world!’;
JavaScript Reserved Keywords
abstract
continue
extends
implements native
static
try
as
const
false
import
new
super
typeof
boolean
debugger
final
in
null
switch
use
break
default
finally
instanceof
package
synchronized
var
byte
do
float
int
private
this
void
case
double
for
interface
protected
throw
volatile
catch
else
function
is
public
throws
while
char
enum
goto
long
return
transient
with
class
export
if
namespace
short
true
You should know this from C or VB
New to JavaScript - we’ll cover these
We won’t cover these
Proposed but not standard
The typeof Operator
Make believe that it’s a function
x=17
alert(typeof(x)); //Number
x=‘17’;
alert(typeof(x)); //String
x=new Date();
alert(typeof(x)); //Object
x=true;
alert(typeof x); //Boolean
typeof always returns a string
Javascript Relational Operators
Standard C relational operators will work too
> < =
>= <= !=
===
!==
matches data type and value
5==“5” is true.
5===“5” is false
JavaScript Logical Operators
These are just like C as well!
• &&
• ||
• !
Flow of Control: if stmt
price=18;
if (age<18 || age>65)
{
total=price*taxRate*.80;
}
else total=price*taxRate;
Flow of Control: Comparing Strings
//This works likes C ought to have worked!
if (sex==‘Female’)
{
alert(‘Hello Madam’);
}
if(password!=‘Swordfish’) alert(‘try again!’);
switch statement
n=prompt(‘Enter any value');
switch(n) //The switch statement will take any scalar data type!
{ case 1:
document.write('We accept numbers');
break;
case true:
document.write('We accept boolean values');
break;
case 4.7:
document.write('we accept floating point numbers');
break;
case 'Humber‘:
case x:
document.write('switch will take a String or match the value of a variable');
break;
default:
document.write('Default case');
}
Looping – Just like C
for(i=0; i<10;i++)
{
idName=‘checkbox’+i;
document.write(‘<input id=“’ + idName + ‘”> ‘
+ i + ‘</input>’);
}
A “for each” loop
var students=['Bob','Mike','Rinky'];
for(i in students)
{
alert(i+ ' ' +students[i]);
}
Associative Arrays
var students=['Bob','Mike','Rinky'];
for(i in students)
{
alert(i+ ' ' +students[i]);
}
Early Exit from a Loop
sum=0;
for(i=0; ;i++)
{
sum+=i;
if(sum>20) break;
}
alert(‘The total is: ‘ + sum);
Skipping to the End of a loop
sum=0;
for(i=0; i<7;i++)
{
if(i==5 || i==3) continue;
sum+=i;
}
alert(sum);
while loops
var counter = 0;
var newLine = ‘<br />’;
document.write(newLine);
while(counter < 10){
document.write(“counter = " + counter);
document.write(newLine);
counter++;
}
document.write(“Done!!");
Functions and Subroutines
function function1(arg1,arg2,arg2)
{
result=arg1+arg2+arg3;
return result;
}
function subroutine1(arg1,arg2)
{
//Do something
return;
}
Some Math Functions
Math.abs(value)
Absolute integer or float
Math.sin(value),
Math.cos(value)
Math.tan(value)
All the trig functions you’d expect.
value is measured in radians.
Math.ceil(value)
Math.floor(value)
Math.round(value)
Rounding functions – note that
round only rounds to the nearest
integer.
Math.random()
Random number between 0 and 1
Math.sqrt(n)
Math.pow(n,m)
nm
Math.min(a,b)
Math.max(a,b)
lesser of two values
greater of two values
Math.log(num)
Math.PI
The value of P
Also asin, acos, atan, atan2, log, exp and a few other items
String Functions
“one,two,three”.split(‘,’)
Creates the array:
[“one”,”two”,”three”]
myString.length
length of string
x=myString.toUpperCase()
x=myString.toLowerCase()
x will be all upper case
x will be all lower case
“George”.substring(2,4)
Value is “org” - we start counting
at 0
“Bananana”.indexOf(“nan”)
“Bananana”.lastIndexOf(“nan”)
returns location ?
returns location ?
“George”.charAt(0)
result is “G”
x=escape(“<br/> This & That?”))
Generates:
%3CBR/%3E%20%26%20This%20
%26%20That%3F%20
the inverse function
y=unescape(string)
These make a string portable to
send over a network.
Date Functions
Warnings:
getMonth() returns a month as a number: 0-11
getDate() returns the day of the month: 1-31
getDay() returns the day of the week: 0-6
x=new Date(2010,12,1); //This is Jan 1, 2011!
x=new Date(2012,2,0); //last day of Febuary, 2012
x=new Date(2012); //This is 2012 millisecs past the EPOCH
Array Functions
[“one”,”two”,”three”].join(“;”)
Creates a string: one;two;three
(it’s the opposite of split)
myArray.length
highest subscript in myArray+1
myArray.reverse()
Reverses the order of elements in the
array.
myArray.slice(2,5)
Creates a new array using elements 2
thru 5 of the old array
The Array slice Function
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write(fruits.slice(0,1) + "<br />");
document.write(fruits.slice(1) + "<br />");
document.write(fruits.slice(-2) + "<br />");
document.write(fruits);
//Output
Banana
Orange,Apple,Mango
Apple,Mango
Banana,Orange,Apple,Mango
Example taken from W3Schools.com
The Array splice Function
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write("Removed: " +
fruits.splice(2,1,"Lemon") + "<br />");
document.write(fruits);
The function returns items removed and modifies the original
array.
Example taken from W3Schools.com
Sorting an Array of Strings
myArray.sort();
Regular Expressions
var str=‘Hello World. Have a nice day!’;
str.replace(/World/,’Canada’);
//result is: ‘Hello Canada. Have a nice day!’;
result=str.replace(/[aeiou]/g,’*’);
//result is ‘H*ll* C*n*d*. H*v* * n*c* d*y!’;
//The original is unchanged
result= str.replace(/H/,’h’);
//Only the first h affected
Most of what you would have learned in “Unix and the Internet” about regular
expressions in vim can be applied here for doing complex search and replace.
The match Function
var str=‘Hello World. Have a nice day!’;
str.match(/[aeiou].?/g);
Returns the following array of matches
[“el”, “o “, “o “, “av”,”a “, “ic”, “e “, “ay”]
str="Monday Tuesday Wednesday Thursday Friday“;
result=str.match(/(Mon|Fri)day/g);
Returns:
[“Monday”, “Friday”]
Debugging
Output to the Error Console
You can send a message to the Error Console – however
this stops the script:
{
.... //Code goes here
if(value>10)
throw new Error(“Your message goes here: “ + value);
}
You can also write to Firebug’s Console
{
console.log(“Your message: “ + yourVariable);
console.log(“C style format allowed: %s, %d, $%8.2f”,
myString, age, cost);
console.debug(“
console.info(“
console.warn(“
console.error(
DOM: The Document Object Model
document as an Object
(document Properties
document.cookie
A list of all cookies sent to the document
as name/value pairs
document.links
An array of all links in the document
document.anchors
An array of all images in the document
document.forms
An array of all forms in the document
document.images
An array of all images in the document
Window as an Object
• To open a new window
Navigator as an Object
Cookies can be set with the Meta tag
<META HTTP-EQUIV="Set-Cookie"
CONTENT="cookievalue=myFirstCookie;expires=30">
<META HTTP-EQUIV="Set-Cookie"
CONTENT="cookievalue3=my3rdCookie;expires=30">
setMessage('myList',document.cookie);
//Result:
cookievalue=myFirstCookie; cookievalue2=my2ndCookie;
cookievalue3=my3rdCookie
Retrieving a Cookie
document.getElementById(id)
•
•
DOM: The Document Object Model
We’ll use this function a lot to get a handle on a specific tag. But to make it more
readable we’ll put it into functions that reflect it’s use:
function setMessage(id,msg)
{
element=document.getElementById(id);
element.innerHTML=msg;
}
function getMessage(id,msg)
{
element=document.getElementById(id);
return element.innerHTML;
}
<p id='when' onclick='setMessage("when",Date())'
onmouseout='alert(getMessage("when"));' > Click for time</p>
For this course use
<script type="text/javascript" src="utilities.js">
(this is available from the directory:
http://munro.humber.ca/~king/NEST401/utilities.js)
Modifiable Tag Properties
innerHTML
<tag id=‘t1’>This can be modified</tag>
change text contents
value
<input id=‘t1’ type=‘text’ value=‘Fred’ />
change a form value
src
<img id=‘t1’ src=‘myImage.jpg’ />
replace or set an image
href
<a href=‘ibm.com’> </a>
alter a hypertext link
checked
<input type=checkbox checked=checked>
alter/check checkbox or
radio button
style
<h1 style=“color:red” > ....
alter/retrieve style info
className
<h1 class=‘Humber’ id=‘tagID’
name=‘fieldName’ >
alter/retrieve class, id or
name info
name
retrieve/alter element name
element=document.getElementById(name);
element.innerHTML=‘<b>any text can be inserted’;
element.src=‘otherImage.jpg’
element.href=newLocation
element.checked=true;
element.style=‘color:green’;
element.className=‘Seneca’; //Note: not class, className!
Retrieve All Tags of a Given Type
function displayPictureNames()
{
images=document.getElementsByTagName("img");
for(id in images)
{
if(images[id].alt==undefined) continue;
alert(id + ' ' + images[id].src);
images
}
}
The Error Console helps debug code
The FireBug Plug in Is Better
•
•
•
•
Watches
Single stepping through code
Call stack
Break points
Advanced Features
The with statement
with (Math) {
a = PI * r*r;
y = r*sin(theta);
x = r*cos(theta)
b = a + y/x;
}
with (myCar) {
setModel(‘Escape’);
display();
}
The idea is similar to with in VBA
Non Primitive Objects
•
•
Idea is similar to types in VBA or structs in C
Allows us to create a non-primitive data type
function Car(nMake, nModel,nYear)
{
this.make=nMake;
this.model=nModel;
this.year=nYear;
this.display=display_car;
this.setModel=setModel; //Not in text
}
function display_car() {
document.write(‘(‘ + this.make +’,’+this.model+’,’+this.year+’)’ );}
function setModel(replacement) { this.model=replacement; }
myCar=new car('Ford','Fairlane',2010);
myCar.setModel(‘Escape’);
myCar.display_car();