introducing javascript. javascript code is triggered by “events” document eventsonload, onunload...

80
Introducing JavaScript

Upload: easter-smith

Post on 29-Dec-2015

240 views

Category:

Documents


0 download

TRANSCRIPT

Introducing JavaScript

Javascript code is triggered by “events”

Document Events onload, onunload

Mouse Events onclick, ondblclickonmousedown, onmouseuponmousemove, onmouseover, onmouseout

Key Events onkeypress, onkeydown, onkeyup

Form Events onfocus, onblur, onselect, onchangeonsubmit, onreset

New events proposed Jan 2010 in HTML5

In 2010 HTML5 Introduced More Events

Clipboard Events oncopy, oncut, onpaste

Mouse Events oncontextmenu, onwheel

Touch Events ontouchcancel, ontouchstart, ontouchmove, ontouchend

Drag Events (drag and drop) ondrag, ondrop, ... (more)

Print Events onbeforeprint, onafterprint

Form Events oninput, oninvalid, onsearch

Animation Events animationstart, animationend, animationiteration

Media Events onpause, onplay, onseeking, onsuspend, onvolumechange.... (and many more)

for a complete list and reference: http://www.w3schools.com/jsref/dom_obj_event.asp

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 pagename: used for radio buttons and name/value

pairs passed in query stringsclass: 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 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 ....

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!

Dictionaries (JSON)

lookup={'John' : '27 Queen Street', 'Harry Potter' : '18 Privet Drive',

'Sherlock Holmes' : '221 Baker Street'};

console.log(lookup); the above javascript object notation dictionary will be output

console.log(lookup['Harry Potter']); 18 Privet Drive

A Dictionary can Contain Anything!

classList={'Sam' : {course: 'CENG256', midterm: 79, exam: 83,

assignments: [18.2,undefined,27,18.5,21.25]},

'Raina' : {course: 'CENG255', midterm: 63, exam: 77, assignments: [27,24,18,29,25.5]}

}

console.log("Midterm Test: %5.2f%%", classList['Raina'].midterm);

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 prefixto indicate the datatype of a variable, named after Charles Simonyi

sFirstName - its a stringbFound - its a booleanasNames - array of stringsdBirth - date

It’s encouraged in Microsoft communities

OperatorsStandard 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 Java

New to JavaScript - we’ll cover these

Proposed but not standard

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!

• &&• ||• !

Bitwise Operators

• >> shift left• << shift right• >>> shift left and don’t propagate the sign bit• <<< - this operator doesn’t exist… why?

More JavaScript Operators

• in• delete• instanceof• new• typeof• void

in

• The in operator can be used to test for the presence of an index in an array or an element in a JSON dictionary

list=[1, 7, 12, 8, 13]if(3 in list) { … }if(‘Maria’ in classList) { … }

• in can also be used in a foreach loop. It will assume the value of each index or key

for(index in list) { … }for(key in classList) { …. }

delete• The delete operator can be used to undefined a variable

x= new Date();delete x; //x no longer exists. Its ‘value’ is undefined

• delete will also remove an element of an array by it’s index

list=[1,2,57,12,3];delete list[3]; //removes ’12’ which is at position 3

• delete will remove an element from a JSON dictionary

delete classList[‘Sam’].midterm;delete classList[‘Sam’][‘midterm];delete classList[‘Emily’];

Object Prototypes (new, this)function Car(nMake, nModel,nYear) { this.make=nMake; this.model=nModel; this.year=nYear; this.setModel=function(replacement) { return this.model=replacement; }; }

myCar=new Car('Ford','Fairlane',1957); myCar.setModel('Escape');

//We can modify the function prototype even after defining itCar.prototype.display_Car=function() { console.log('make: %s model: %s year: %d', this.make,this.model,this.year); return true; } ;

myCar.display_Car();

More on this

• this can also be used to refer to the current tag in an inline script

<input id=myTag name=Bobondrag=“alert(this.id+”:”+this.name);” type=input width=10 >

instanceof

• instanceof is used to test if a variable belongs to a particular class

if(myCar instanceof Car) { …}if(myDate instanceof Date) { ….}

void

• void is used to ensure that an expression doesn’t return a value:

void i++; //i is incremented, but the line does //not return a value

• void is often used to signify that an event doesn’t propagate

<input type=button onclick=“javascript:void(0)” value=‘Do Nothing’>

[] .

• [] and . are called the member of operators. In JavaScript they do the same thing

myList[‘Sam’]= {midterm: 68, ‘final’: 79 }myList.Raina={midterm: 68, ‘final’ : 82 }

We tend not to think of [] and . As operators, but it is useful to consider them as such.

,

• The comma is an operator too. It separates items in a list. If used in an assignment it returns the last value

x= myFunction1(),myFunction2(),7+9,i++,18,’//x will be 18

This secondary use of , is rare – but it also works in C and Java too

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]); }

JSON and for each loops

for(key in lookup) console.log("name: %s address: %s“, key, lookup[key]);

The typeof Operator

Make believe that it’s a functionx=17

alert(typeof(x)); //Numberx=‘17’; alert(typeof(x)); //Stringx=new Date();alert(typeof(x)); //Objectx=true;alert(typeof x); //Boolean

typeof always returns a string

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; //no return value }

Closures: map

list=[1,2,3,4]; console.log(list);

Array [ 1, 2, 3, 4 ]

console.log(myClosure(17)); 289

console.log(list.map(Math.sqrt)); Array [ 1, 1.4142135623730951, 1.7320508075688772, 2 ]

console.log(list.map(myClosure));Array [ 1, 4, 9, 16 ]

Closures: reduce list=[1, 2, 57,3,4]

//Return the odd numbers only oddNums=list.reduce(function(prev,curr)

{ if(curr%2==1) return prev.concat(curr); else return prev; },[]);

console.log(oddNums);

//Find the maximum value of a list maxvalue=list.reduce(function(prev,curr) { if(prev == undefined) return curr;

if(prev > curr) return prev; return curr; });

console.log("Maximum value is: ",maxvalue);

Classes

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() { console.log(‘(‘ + this.make +’,’+this.model+’,’+this.year+’)’ );}

function setModel(replacement) { this.model=replacement; }

myCar=new car('Ford','Fairlane',1957); myCar.setModel(‘Escape’); myCar.display_car();

Some Math FunctionsMath.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 valuesgreater 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 casex 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?”))

y=unescape(string)

Generates: %3CBR/%3E%20%26%20This%20%26%20That%3F%20the inverse function

These make a string portable to send over a network.

y=

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

myArray.map(function) Creates a new array by applying the function to each of the elements of the array.

JSON stringify and parse

myString=JSON.stringify(classList);

classList2=JSON.parse(myString)

The stringify function converts a dictionary into a readable string. The parse function converts a string (in the right format) into a dictionary. This is used to move date between client and server.

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);

//OutputBananaOrange,Apple,MangoApple,MangoBanana,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 regularexpressions 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(fmt, arg1, arg2, ...) console.info(fmt, arg1, arg2, ...) console.warn(fmt, arg1, arg2, ...) console.error(fmt, arg1, arg2, ...)

DOM: The Document Object Model

window as an Object(document Properties

window.document The current document

window.history The history object

window.innerHeight, window.innerWidth The current window’s size

Window.navigator Information about the browser

Window.console Gives one a handle on the console object

Window.location The current URL (can be reset)

Window.screenX, window.screenY Position on the screen. Also methods moveTo and moveBy

window.frames Used with framesets where the window can have multiple frames

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

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

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>

Element.attributes<p id='when' onclick=“setMessage(‘when’,Date())” onmouseout='alert(getMessage("when"));' name=Fred > Click for time</p>

element=document.getElementById(‘when’); attribs=element.attributes;

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 PropertiesinnerHTML <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=newLocationelement.checked=true; element.style=‘color:green’;element.className=‘Seneca’; //Note: not class, className!

Modifiable style PropertiesCSS Name JavaScript Name Purpose

color color e.style.color=“red”

background-color backgroundColor e.style.backgroundColor=“rgb(0,100,200)”

font-size fontSize e.style.fontSize=32

margin-left marginLeft e.style.marginLeft=“20%”

List-style-image listStyleImage e.style.listStyleImage=“url(‘bsdemon.jpg’)”

The full list is huge. Generally one takes the style name and uses it in camelCaps. If the style name has an embedded dash – remove it as JavaScript would see it as a subtraction symbol. See: http://www.w3schools.com/cssref/

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

} }

Manipulating DOM Structure

document.createElement

• This function creates a new node which can then be inserted into the document:

newList=createElement(“ol”);newPara=createElement(“li”);

document.createAttribute

• This creates a new attribute which we can then add to our element.

• If we had to do a lot of them this could take some time…..

So……

Wait for next week….

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