Javascript - LINK@KoreaTech

advertisement

Javascript

2012. 10

Youn-Hee Han

LINK@KOREATECH http://link.koreatech.ac.kr

[Practice-1] My First Javascript

 Javascript Example 1

<html>

<head>

<script type="text/javascript"> function displayDate() { document.getElementById("demo").innerHTML=Date();

}

</script>

</head>

<body>

<h1>My First Web Page</h1>

<p id="demo">This is a paragraph.</p>

<button type="button" onclick="displayDate()" >Display Date</button>

</body>

</html>

LINK@KOREATECH 2

Client-side scripting

 Scripts can be embedded in the HTML.

– Most popular scripting language is JavaScript.

 Scripts can access and change the contents of a Web page.

– Assist in completion and checking of forms.

– Provides user control of client-side of page appearance and content.

 Scripts are interpreted and executed, line by line, whenever they are needed

– This means that “syntax errors” as well as “logic errors” appear when the html is being produced

LINK@KOREATECH 3

JavaScript

 Role of Javascript

– Adds functionality to web pages

– designed to add interactivity to HTML pages

 Features

– Scripting language

• Easy and Fast Implement

– Runs on the client side

• interpreter is embedded in the browser

– Makes it possible to change HTML elements and their properties

• Dynamic HTML (DHTML)

– Makes it possible to change HTML elements’ body contents

– JavaScript = ECMA-Script

– Syntax like C

LINK@KOREATECH 4

JavaScript vs. Java

 JavaScript is quite different from Java

– Similar syntax

• because they both descend from C

– Java is strongly typed

– Java is compiled (into byte code)

• actually hybrid because byte code is mostly interpreted

– Java has strong Object Oriented foundation

• JavaScript has a similar level of OO foundation

 The name was primarily a “marketing decision”

– Sun and Netscape against Microsoft

LINK@KOREATECH 5

JavaScript’s Role

 What Can JavaScript do?

– JavaScript gives HTML designers “a programming tool”

• Almost anyone can put small "snippets" of code into their HTML pages

– JavaScript can react to events

• A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element

– JavaScript can read and write HTML elements

• A JavaScript can read and change the content of an HTML element

LINK@KOREATECH 6

JavaScript’s Role

 What Can JavaScript do?

– JavaScript can be used to validate data

• A JavaScript can be used to validate form data before it is submitted to a server.

• This saves the server from extra processing

– JavaScript can be used to detect the visitor's browser

• A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser

– JavaScript can be used to create cookies

• A JavaScript can be used to store and retrieve information on the clinet's computer

LINK@KOREATECH 7

Form validation

 The data that the user enters MUST be checked when it arrives at the server-side

– If there is an error, the user must get a warning about this and asking for correct data

 It is resource-consuming (time and network) to send incorrect data over the web

– Partial solution – check this first with javascript on the client side and secondly check the remains on the server side.

LINK@KOREATECH 8

[Practice-2] Experience the validation function

 Visit

– http://www.xs4all.nl/~sbpoley/webmatters/formval.html

LINK@KOREATECH 9

<script> Element

<script src="login.js" language="text/javascript">

</script>

 <script> element

– either contains scripts

• an entire program can be placed there

– or contains reference to external scripts file

• this is the preferred way!

 src attribute

– URL of a file with an external script

– standard file extension .js for JavaScript source files

 language (or type) attribute

– specifies the scripting language used

– text/javascript for JavaScript

LINK@KOREATECH 10

JavaScript in a Web Page

 Typically, <script> is placed within the <head> element of the

XHTML document

– the contents inside <head> is interpreted first

– this is the preferred way

 But <script> elements can be placed in the <body> element, too

– they are executed in the order in which they appear in the HTML document

LINK@KOREATECH 11

Writing a Web Page

 The DOM document object

– represents the HTML document of the web page currently displayed in the browser

 document.write() or document.writeln()

– insert XHTML code into the XHTML document

– once the page is rendered, document.write() is executed

– this allows us to specify (portions of) a web page via scripting!

 alert()

– displays a dialog with message passed a the argument string

 prompt()

– displays a dialog with message passed a the argument string

– and an input field where the user can type a text

LINK@KOREATECH 12

JavaScript Where To

 JavaScripts can be put in the <body> and in the <head> sections of an HTML page.

– It is a common practice to put “all functions” in the <head> section

– JavaScript is usually executed when an event occurs, such as when a user clicks a button.

 JavaScript in <body>

– JavaScript is placed at the bottom of the page

• to make sure it is not executed before the accessed elements are created.

• Javascript at the bottom of the page does not interfere with page content.

LINK@KOREATECH 13

Javascript for Dynamic HTML

 Dynamic effects

– Pop-up menus, rollover images

• Particularly when mouse moves over image

 Opening additional browser windows

– Possibly for ‘help’ or adverts

– More difficult to manage multiple related windows, so best used sparingly

 Opening dialogue boxes for communication with user

– ‘alert’ : invalid data

– ‘confirm’ : e.g. submit this data? Message, OK and Cancel buttons

– ‘prompt’ : message and text field for data entry

 Modifying web page content

– For instance adding date or highlighting errors in form

LINK@KOREATECH 14

Javascript Syntax - basic

 Unlike HTML, JavaScript is case sensitive

 Comments

– // - single line comment

– /* … */ - multi line comment

 Return statement in a function

<html> <head>

<script type="text/javascript"> function product(a,b) { return a*b; // return statement

}

</script></head>

<body>

<script type="text/javascript"> document.write(product(4,3));

</script>

</body>

</html>

LINK@KOREATECH 15

Javascript Syntax - variable

 Declaring (Creating) JavaScript Variables var x; var a; var thisIsAVariable; var _and_this_too; var mix12three; var carname; var 2three4five; // (X) you can't start with a number var x=5; var carname="Volvo", carprice=3000; var v1, v2, v3 = 'hello', v4 = 4, v5;

 Variables are Case Sensitive var case_matters = 'lower'; var CASE_MATTERS = 'upper';

LINK@KOREATECH 16

Javascript Syntax - variable

 Local variable vs. Global variable

– A variable declared within a JavaScript function becomes LOCAL and can only be accessed within that function.

– Variables declared outside a function become GLOBAL , and all scripts and functions on the web page can access it.

– If you assign values to variables without “var”, the variables will automatically be declared as GLOBAL x=5; carname="Volvo";

LINK@KOREATECH 17

Javascript Syntax – operators (1/5)

 JavaScript Arithmetic Operators

LINK@KOREATECH 18

Javascript Syntax – operators (2/5)

 Adding Strings and Numbers

– The + operator can be used to add string variables or text values together

– If you add a number and a string, the result will be a string!

<html>

<body>

<script type="text/javascript"> var txt1="What a very“, var txt2="nice day"; var txt3=txt1+" "+txt2; document.write(txt3 + "<br />"); var x; x=5+5; document.write(x + "<br />"); x="5"+"5"; document.write(x + "<br />"); x=5+"5"; document.write(x + "<br />"); x="5"+5; document.write(x + "<br />");

</script>

</body>

</html>

LINK@KOREATECH 19

Javascript Syntax – operators (3/5)

 ++, --

<html>

<head>

<script type="text/javascript"> var a = 123; var b = a++; document.write("a: " + a +", b: " + b + "<br />"); var a = 123; var b = ++a; document.write("a: " + a +", b: " + b + "<br /><br />"); var a = 123; var b = a--; document.write("a: " + a +", b: " + b + "<br />"); var a = 123; var b = --a; document.write("a: " + a +", b: " + b + "<br />");

</script>

</head>

<body>

</body>

</html>

LINK@KOREATECH 20

Javascript Syntax – operators (4/5)

 Comparison Operators

– [NOTE] x == “5” is true and 5 == “5” is true

– [NOTE] NaN == NaN is false

 Logical Operators

LINK@KOREATECH 21

Javascript Syntax – operators (4/5)

 Lazy Evaluation

<html>

<body>

<script type="text/javascript"> var b = 5; if (true || (b = 6)) document.write(b + "<br />"); if (true && (b = 6)) document.write(b + "<br />");

</script>

</body>

</html>

LINK@KOREATECH 22

Javascript Syntax – Primitive Data Type (1/10)

 In javascript, any value that you use is of a certain type

 Five Primitive Data Types

– number

• It includes floating point numbers as well as integers

• for example 1, 100, 3.14, Infinity, -Infinity

– string

• any number of characters, for example "a", "one", "one 2 three“

– boolean

• can be either “true” or “false”

– undefined

• You get the special value “undefined” for a variable that doesn't exist

• You get “undefined” for a value when you have declared, but not given it a value yet.

– null

• It is another special data type that can have only one value, the “null” value.

• It means no value or nothing

• The difference with “undefined”

 if a variable has a value “null”, it is still defined

LINK@KOREATECH 23

Javascript Syntax – Primitive Data Type (2/10)

 Any value that doesn't belong to one of the five primitive types listed above is an object .

– Even “null” is considered an object, which is a little awkward

• “null” is an object (something) that is actually nothing

– “string” is also considered an object, which is also a little awkward

 Remember that in JavaScript the data types are either:

– Primitive (the five types listed above), or

– Non-primitive (objects)

LINK@KOREATECH 24

Javascript Syntax – Primitive Data Type (3/10)

 typeof operator

– returns a string that represents the data type

– return values

• "number", "string", "boolean", "undefined", "object", or "function“

[Infinity]

- It represents a number too big

- “typeof Infinity” returns “number”

- the biggest number JavaScript can handle is

1.7976931348623157e+308 while the smallest is 5e-324

[NaN]

- It represents ‘not a number’

- “typeof NaN” returns “number”

- the biggest number JavaScript can handle is

1.7976931348623157e+308 while the smallest is 5e-324

LINK@KOREATECH 25

Javascript Syntax – Primitive Data Type (4/10)

 Examples

<html>

<head>

<script type="text/javascript"> var a = 123; var b = 2e+3; var c = 123.456E-3; document.write(typeof a + "<br/>"); document.write(typeof b + "<br/>"); document.write(typeof c + "<br/>"); document.write(b + "<br/>"); document.write(c + "<br/><br/>"); var d = Infinity; var e = 6 / 0; var f = -Infinity; document.write(typeof d + "<br/>"); document.write(typeof e + "<br/>"); document.write(typeof f + "<br/>"); document.write(d * 2 + "<br/>"); document.write(e + "<br/>"); document.write(f + "<br/><br/>"); var g = NaN; var h = 10 * "f"; var i = 1 + 2 + NaN; document.write(typeof g + "<br/>"); document.write(typeof h + "<br/>"); document.write(typeof i + "<br/>"); document.write(g + "<br/>"); document.write(h + "<br/>"); document.write(i + "<br/>");

</script>

</head>

<body>

</body>

26

Javascript Syntax – Primitive Data Type (5/10)

 Examples

<html>

<head>

<script type="text/javascript"> var s1 = "some characters"; var s2 = 'some characters and numbers 123 5.87'; var s3 = '1'; var s4 = ""; var s5 = s1 + s2; document.write(typeof s1 + "<br/>"); document.write(typeof s2 + "<br/>"); document.write(typeof s3 + "<br/>"); document.write(typeof s4 + "<br/>"); document.write(typeof s5 + "<br/>"); document.write(s5 + "<br/>");

</script>

</head>

<body>

</body>

</html>

LINK@KOREATECH 27

Javascript Syntax – Primitive Data Type (6/10)

 String Conversions

– When you use a number-like string as an operand in an arithmetic operation, the string is converted to a number behind the scenes.

– This works for all operations except addition

<html>

<head>

<script type="text/javascript"> var s = '2'; s = 3 * s; document.write(typeof s + "<br/>"); document.write(s + "<br/><br/>"); var s4 = '101 dalmatians'; s4 = s4 * 10; document.write(typeof s4 + "<br/>"); document.write(s4 + "<br/><br/>"); var n = 1; n = "" + n; document.write(typeof n + "<br/>"); document.write(n + "<br/><br/>"); var s2 = '1'; s2++; document.write(s2 + "<br/><br/>"); var s3 = "100"; document.write(typeof s3 + "<br/>"); s3 = s3 * 1; document.write(typeof s3 + "<br/>"); document.write(s3 + "<br/><br/>"); document.write("" + null + "<br/>"); document.write("" + undefined + "<br/>");

</script>

</head>

<body>

</body>

</html>

LINK@KOREATECH 28

Javascript Syntax – Primitive Data Type (7/10)

 Special String

LINK@KOREATECH 29

Javascript Syntax – Primitive Data Type (8/10)

 Create an Boolean variable

– The boolean variable represents two values: "true" or "false".

– If the boolean variable has no initial value, or if the assigned value is one of the followings, it is set to false

• 0

• -0

• null

• ""

• false

• undefined

• NaN

– For any other value, it is set to true (even with the string "false")!

LINK@KOREATECH 30

Javascript Syntax – Primitive Data Type (9/10)

 Boolean variable example

<html>

<body>

<script type="text/javascript"> var b1=0; var b2=1; var b3=""; var b4=null; var b5=NaN; var b6="false"; var b7; document.write(typeof b1 + "<br />"); document.write("0 is boolean <b>"+ !!b1 +"</b><br />"); document.write("1 is boolean <b>"+ !!b2 +"</b><br />"); document.write("An empty string is boolean <b>"+ !!b3 + "</b><br />"); document.write("null is boolean <b>"+ !!b4+ "</b><br />"); document.write("NaN is boolean <b>"+ !!b5 +"</b><br />"); document.write("The string 'false' is boolean <b>"+ !!b6 +"</b><br />"); document.write("The type of b7 is <b>"+ (typeof b7) +"</b><br />"); document.write("Undefined is boolean <b>"+ !!b7 +"</b><br />");

</script>

</body>

</html> LINK@KOREATECH 31

Javascript Syntax – Primitive Data Type (10/10)

 "undefined“, “NaN”, and “null” example

<html>

<body>

<script type="text/javascript"> document.write(typeof foo + "<br/><br/>"); var a = 1 * undefined; document.write(a + "<br/>"); document.write(typeof a + "<br/><br/>"); var somevar; document.write(somevar + "<br/>"); document.write(typeof somevar + "<br/><br/>"); var somevar2 = null; document.write(somevar2 + "<br/>"); document.write(typeof somevar2 + "<br/><br/>"); var c = 1 * null; document.write(c + "<br/>"); document.write(typeof c + "<br/><br/>");

</script>

</body>

</html> var i = 1 + undefined; document.write(i + "<br/>"); document.write(typeof i + "<br/><br/>"); var k = 1 + null; document.write(k + "<br/>"); document.write(typeof k + "<br/><br/>");

LINK@KOREATECH 32

Javascript Syntax – conditional statements

 Conditional Statements

– if statement

<html>

<body>

<script type="text/javascript"> var r=Math.random(); if (r>0.5) { document.write("<a href='http://www.kut.ac.kr'>Visit KUT</a>");

} else { document.write("<a href='http://cse.kut.ac.kr'>Visit CSE-KUT!</a>");

}

</script>

</body>

</html>

LINK@KOREATECH 33

Javascript Syntax – conditional statements

 Conditional Statements

– Checking if a Variable Exists

<html>

<body>

<script type="text/javascript"> var somevar document.write(typeof somevar + "<br/>"); var result = 'no'; if ( somevar ) {result = 'yes';} if ( typeof somevar !== "undefined" ) {result = 'yes';} document.write(result + "<br/>");

//if (somevar2) {result = 'yes';} if ( typeof somevar2 !== "undefined" ) {result = 'yes';} document.write(result + "<br/>");

</script>

</body>

</html>

LINK@KOREATECH 34

Javascript Syntax – conditional statements

 Conditional Statements

– Alternative if Syntax var result = (a === 1) ? "a is one" : "a is not one";

LINK@KOREATECH 35

Javascript Syntax – conditional statements

 Conditional Statements

– switch .. case

• switch (expression) { case value1: statement; break; case value2: statement; break;

… default: statement;

}

• Expression can be almost ANY!!!

 integer, character

 string

» See http://www.javascriptkit.com/javatutors/switch.shtml

 constant

» See http://drj11.wordpress.com/2007/09/03/javascript-switch/

LINK@KOREATECH 36

Javascript Syntax – conditional statements

 Conditional Statements

– switch .. case var a = '1'; var result = ''; switch (a) { case 1: result = 'Number 1'; break; case '1': result = 'String 1'; break; default: result = 'I don\'t know'; break;

} document.write(result + "<br/>");

LINK@KOREATECH 37

 For loop

Javascript Syntax – loop (1/4)

 while loop

<html>

<body>

<script type="text/javascript"> for (i = 1; i <= 6; i++) { document.write("<h" + i + ">This is heading " + i); document.write("</h" + i + ">");

}

</script>

</body>

</html>

<html>

<body>

<script type="text/javascript"> var i=0; while (i<=5) { document.write(“Num: " + i + "<br />"); i++;

}

</script>

</body>

</html>

<html>

<body>

<script type="text/javascript"> var i=0; do { document.write(“Num: " + i + "<br />"); i++;

} while (i<=5);

</script>

</body>

</html>

LINK@KOREATECH 38

Javascript Syntax – loop (2/4)

 For loop

} var punishment = ''; for (var i = 0; i < 100; i++) { punishment += 'I will never do this again, ';

} for (var i = 0, punishment = ''; i < 100; i++) { punishment += 'I will never do this again, ';

} for (var i = 0, punishment = ''; i < 100; i++, punishment += 'I will never do this again, ') {

// nothing here

} var i = 0, punishment = ''; for (;;) { punishment += 'I will never do this again, '; if (++i == 100) { break;

}

LINK@KOREATECH 39

 break

 continue

Javascript Syntax – loop (3/4)

<html>

<body>

<script type="text/javascript"> var i=0; for (i=0;i<=10;i++) { if (i==3) break; document.write("The number is " + i + "<br />");

}</script>

</body>

</html

<html>

<body>

<script type="text/javascript"> var i=0; for (i=0;i<=10;i++) { if (i==3) continue; document.write("The number is " + i + "<br />");

}</script>

</body>

</html

LINK@KOREATECH 40

Javascript Syntax – loop (4/4)

 JavaScript For...In Statement

<html>

<body>

<script type="text/javascript"> var a = ['a', 'b', 'c', 'x', 'y', 'z']; var result = ''; for (var i in a) {

} result += 'index: ' + i + ', value: ' + a[i] + '<br/>'; document.write(result);

</script>

</body>

</html>

<html>

<body>

<script type="text/javascript"> var person=["John","Doe", 25]; for ( x in person ) { document.write(x + " ");

} document.write("<br />"); for ( x in person ) { document.write(person[x] + " ");

}

</script>

</body>

</html>

LINK@KOREATECH 41

Javascript Syntax – Cache an error

 The try...catch Statement

<html>

<head>

<script type="text/javascript"> var txt=""; function message() { try { alertt("Welcome guest!"); // mis-spell!!!

} catch(err) {

} txt="There was an error on this page.\n\n"; txt+="Click OK to continue viewing this page,\n"; txt+="or Cancel to return to the LINK@KUT laboratory page.\n\n"; if(!confirm(txt)) { // confirm function will return true or false document.location.href="http://link.kut.ac.kr";

}

}

</script>

</head>

<body>

<input type="button" value="View message" onclick="message()" />

</body>

</html>

LINK@KOREATECH 42

Javascript – HTML Events

 Window Events

– Only valid in body and frameset elements.

Attribute Value onload script onunload script

Description

Script to be run when a document loads

Script to be run when a document unloads

 Form Element Events

– Only valid in form elements

Attribute Value onchange script onsubmit script onreset script onselect script onblur script onfocus script

Description

Script to be run when the element changes

Script to be run when the form is submitted

Script to be run when the form is reset

Script to be run when the element is selected

Script to be run when the element loses focus

Script to be run when the element gets focus

LINK@KOREATECH 43

Javascript – HTML Events

 Window Events Example

<html>

<head>

<script type="text/javascript"> function load() { window.status="Page is loaded";

}

</script>

</head>

<body onload="load()" >

</body>

</html>

<html>

<head>

<script type="text/javascript">

} function mymessage() { alert("This message was triggered from me");

</script>

</head>

<body onload="mymessage()" >

</body>

</html>

LINK@KOREATECH 44

Javascript – HTML Events

 Form Element Events Example - onchange

<html>

<head>

<script type="text/javascript"> function upperCase(x) { var y=document.getElementById(x).value; document.getElementById(x).value=y.toUpperCase();

}

</script>

</head>

<body>Enter your name:

<input type="text" id="fname" onchange="upperCase(this.id)" >

</body>

</html>

LINK@KOREATECH 45

Javascript – HTML Events

 Form Element Events Example – onblur

– The onblur event occurs when an object loses focus.

<html>

<head>

<script type="text/javascript"> function upperCase() { var x=document.getElementById("fname").value; document.getElementById("fname").value=x.toUpperCase();

}

</script>

</head><body>Enter your name:

<input type="text" id="fname" onblur="upperCase()" >

</body>

</html>

LINK@KOREATECH 46

Javascript – HTML Events

 Form Element Events Example – onselect

– It occurs when text is selected in a text or textarea field.

<html>

<body>

<form>

Select text: <input type="text" value="Hello world!" onselect="alert('You have selected some of the text.')" >

<br />

<br />

Select text: <textarea cols="20" rows="5" onselect="alert('You have selected some of the text.')" >

Hello world!

</form>

</body>

</html>

LINK@KOREATECH 47

Javascript – HTML Events

 Keyboard Events

– Not valid in br, frame, frameset, head, html, iframe, meta, param, script, style, and title elements.

Attribute Value onkeydown script onkeypress script onkeyup script

Description

What to do when key is pressed

What to do when key is pressed and released

What to do when key is released

LINK@KOREATECH 48

Javascript – HTML Events

 Keyboard Events Example - onkeydown

<html><body>

<script> cnt=1; function showkey(){ if (cnt%20==0){ cnt=1; showchar.innerHTML+='<br>'; showcode.innerHTML+='<br>';

} cnt++; showchar.innerHTML+='('+String.fromCharCode(event.keyCode)+') '; showcode.innerHTML+='('+event.keyCode+')';

}

</script>

입력: <input id="textobj" type="text" onkeydown="showkey()" onfocus="this.style.backgroundColor='cfc'" onblur="this.style.backgroundColor='fff'">

<hr/>

<div id="showchar" class="showclass"></div>

<hr/>

<div id="showcode" class="showclass"></div>

</body></html>

LINK@KOREATECH 49

Javascript – HTML Events

 Mouse Events

– Not valid in br, frame, frameset, head, html, iframe, meta, param, script, style, and title elements.

Attribute onclick ondblclick

Value Description script What to do on a mouse click script What to do on a mouse double-click onmousedown script What to do when mouse button is pressed onmousemove script What to do when mouse pointer moves onmouseout script What to do when mouse pointer moves out of an element onmouseover script What to do when mouse pointer moves over an element onmouseup script What to do when mouse button is released

LINK@KOREATECH 50

Javascript – HTML Events

 Keyboard Events Example - onkeydown

<html>

<body>

<script> function mouseTest(){ str='event.srcElement.tagName='+event.srcElement.tagName+'<BR>'; str+='event.srcElement.id='+event.srcElement.id+'<BR>'; str+='event.srcElement.type='+event.srcElement.type+'<BR>'; str+='event.type='+event.type+'<BR>'; show.innerHTML=str;

}

</script>

<body onmousedown="mouseTest()" >

<table border=1 width=300>

<th id="thObj">마우스로 클릭!</th>

<tr><td><button id="butObj">클릭!</button></td></tr>

<tr><td><input type="text" id="tdObj" value="클릭!"></td></tr>

<tr><td><span id="spanObj">클릭!</span></td></tr>

</table>

<div id="show" style="height:5em;border:solid 1 blue;width:300"></div>

<body>

<html>

LINK@KOREATECH 51

Javascript – Objects Introduction

 JavaScript is an Object Oriented Programming (OOP) language

– you can define your own objects and make your own variable types.

 Properties

– the values associated with an object

<script type="text/javascript"> var txt="Hello World!"; document.write(txt.

length ); // output  12

< /script>

 Methods

– the actions that can be performed on objects

<script type="text/javascript"> var txt="Hello world!"; document.write(txt.

toUpperCase() ); // output  HELLO WORLD!

< /script>

LINK@KOREATECH 52

Javascript – Object Introduction

 Javascript primitive objects

– String

– Date

– Array

– Boolean

– Math

– RegExp

 Javascript objects examples

– See http://www.w3schools.com/js/js_ex_objects.asp

 Javascript objects references

– See http://www.w3schools.com/jsref/default.asp

LINK@KOREATECH 53

Javascript – Array (1/3)

 Create an Array var myCars=new Array(); // regular array myCars[0]="Saab"; myCars[1]="Volvo"; myCars[2]="BMW"; var myCars=new Array("Saab","Volvo","BMW"); // condensed array var myCars=["Saab","Volvo","BMW"]; // literal array

 Modify and print out values in an Array myCars[0]="Opel"; document.write(myCars[0]); var a = [1,2,3]; a[2] = 'three'; document.write(a); // [1, 2, "three"]

LINK@KOREATECH 54

 Modify an Array

Javascript – Array (2/3)

var a = [1,2,3]; a[2] = 'three'; document.write(a); // [1, 2, "three"] a[3] = 'four'; document.write(a); // [1, 2, "three", "four"] a[6] = 'new'; document.write(a); // [1, 2, 3, undefined, undefined, undefined, "new"] delete a[1]; document.write(a); // [1, undefined, 3, undefined, undefined, undefined, "new"]

– An array can contain any type of data, including other arrays

LINK@KOREATECH 55

Javascript – Array (3/3)

 Array of array var a = [1, "two", false, null, undefined]; a[5] = [1,2,3]; document.write(a); // [1, "two", false, null, undefined, [1, 2, 3]] var a = [[1,2,3], [4,5,6]]; document.write(a[0]); document.write(a[0][0]); document.write(a[1][2]); var s = 'one'; document.write(s[0]); document.write(s[1]); document.write(s[2]);

// [1, 2, 3]

// 1

// 6

// “o”

// “n”

// “e”

 More examples

– See http://www.w3schools.com/js/js_obj_array.asp

– See http://www.w3schools.com/jsref/jsref_obj_array.asp

LINK@KOREATECH 56

Javascript – RegExp Object (1/4)

 Create a RegExp object

– Syntax var patt=new RegExp(pattern, modifiers); or more simply: var patt=/pattern/modifiers; var patt=/pattern/  no modifier

– Modifiers

• The i modifier is used to perform casein sensitive matching.

• The g modifier is used to perform a global match (find all matches rather than stopping after the first match).

LINK@KOREATECH 57

Javascript – RegExp Object (2/4)

 RegExp object Examples

– Example 1

– Example 2

<html>

<body>

<script type="text/javascript"> var str = "Visit LINKLab. at KoreaTech"; var patt1 = /linklab/ i ; document.write(str.

match (patt1) + "<br/>"); patt1 = /linklab/; document.write(str.

match (patt1));

</script>

</body>

</html>

<html>

<body>

<script type="text/javascript"> var str="Is this all there is?"; var patt1=/is/ g ; document.write(str.match(patt1) + "<br/>"); var patt1=/is/ gi ; document.write(str.match(patt1));

</script>

</body>

</html>

LINK@KOREATECH 58

Javascript – RegExp Object (3/4)

 RegExp object Examples

– test() – example

• Return true or false

<html>

<body>

<script type="text/javascript"> var patt1=new RegExp("est"); document.write(patt1.

test ("The best things"));

</script>

</body>

</html>

– exec() – example

• Return the matched string

<html>

<body>

<script type="text/javascript"> var patt1=new RegExp("est"); document.write(patt1.

exec ("The best things"));

</script>

</body>

</html>

LINK@KOREATECH 59

Javascript – Browser Objects

 Browser Objects

– Window

– Navigator

– Screen

– History

– Location

 Browser Objects Reference

– See http://www.w3schools.com/jsref/default.asp

LINK@KOREATECH 60

Javascript – Browser Detection

 Navigator object

– The Navigator object contains information about the visitor's browser

<html>

<body>

<div id="example"></div>

<script type="text/javascript"> txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>"; txt+= "<p>Browser Name: " + navigator.appName + "</p>"; txt+= "<p>Browser Version: " + navigator.appVersion + "</p>"; txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>"; txt+= "<p>Platform: " + navigator.platform + "</p>"; txt+= "<p>User-agent header: " + navigator.userAgent + "</p>"; document.getElementById("example").innerHTML=txt;

</script>

</body>

</html>

LINK@KOREATECH 61

Javascript – popup (1/2)

 Popup Boxes

– Alert Box, Confirm Box, Prompt Box

}

<html>

<head>

<script type="text/javascript"> function show_alert() { alert("I am an alert box!");

} function show_confirm() { var r=confirm("Press a button"); if (r==true) alert("You pressed OK!"); else alert("You pressed Cancel!");

LINK@KOREATECH 62

Javascript – popup (2/2)

 Popup Boxes

– Alert Box, Confirm Box, Prompt Box function show_prompt() { var name=prompt("Please enter your name","Harry Potter"); if (name!=null && name!="") document.write("Hello " + name + "! How are you today?");

}

</script>

</head>

<body>

<input type="button" onclick="show_alert()" value="Show alert box" />

<input type="button" onclick="show_confirm()" value="Show confirm box" />

<input type="button" onclick="show_prompt()" value="Show prompt box" />

</body>

</html>

LINK@KOREATECH 63

Javascript – Cookie

 Create and Get Cookie – 1/2

}

<html>

<head>

<script type="text/javascript"> function getCookie(c_name) { var i, x, y; var cookies = document.cookie

.split(";"); for (i = 0; i < cookies.length; i++) { x=cookies[i].substr(0, cookies[i].indexOf("=")); y=cookies[i].substr(cookies[i].indexOf("=") + 1); if (x == c_name) return y;

}

} function setCookie(c_name, value, exdays) { var exdate = new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value = value + "; expires=" + exdate.toUTCString()); document.cookie

= c_name + "=" + c_value; alert("The following cookie is set: \r\n" + c_value);

LINK@KOREATECH 64

Javascript – Cookie

 Create and Get Cookie – 2/2 function checkCookie() { var username=getCookie("username"); if (username != null && username != "") { alert("Welcome again " + username);

} else { username=prompt("Please enter your name:",""); setCookie("username", username, 365);

}

}

</script>

</head>

<body onload="checkCookie()">

</body>

</html>

LINK@KOREATECH 65

Javascript – Form Validation

 Form Validation

<html>

<head>

<script type="text/javascript"> function validateForm() { var x=document.forms["myForm"]["fname"].value; if (x==null || x=="") { alert("First name must be filled out"); return false;

}

}

</script>

</head>

<body>

<form name="myForm" action="demo_form.jsp" onsubmit="return validateForm()" method="post">

First name: <input type="text" name="fname">

<input type="submit" value="Submit">

</form>

</body>

</html>

LINK@KOREATECH 66

Javascript – Timing

 Set Timeout

<html>

<head>

<script type="text/javascript"> function timedText() { var t1= setTimeout ("document.getElementById('txt').value='2 seconds!'", 2000); var t2= setTimeout ("document.getElementById('txt').value='4 seconds!'", 4000);

} var t3= setTimeout ("document.getElementById('txt').value='6 seconds!'", 6000);

</script>

</head>

<body>

<form>

<input type="button" value="Display timed text!" onclick= "timedText()" />

<input type="text" id="txt" />

</form>

</body>

</html>

LINK@KOREATECH 67

Javascript – Timing

 Infinite Timeout

<html>

<head><script type="text/javascript"> var c=0, t, timer_is_on=0; function timedCount() { document.getElementById('txt').value=c; c=c+1; t= setTimeout("timedCount()", 1000) ;

} function doTimer() { if (!timer_is_on) { timer_is_on=1; timedCount();

}

}

</script></head>

<body><form>

<input type="button" value="Start count!" onClick= "doTimer()">

<input type="text" id="txt">

</form></body>

</html>

LINK@KOREATECH 68

Javascript – Timing

 Cancel Timeout – 1/2

}

<html>

<head>

<script type="text/javascript"> var c=0; var t; var timer_is_on=0; function timedCount() { document.getElementById('txt').value=c; c=c+1; t=setTimeout("timedCount()", 1000) ;

} function doTimer() {

} if (!timer_is_on) { timer_is_on=1; timedCount();

LINK@KOREATECH 69

Javascript – Timing

 Cancel Timeout – 2/2 function stopCount() { clearTimeout(t); c=0; timer_is_on=0;

}

</script>

</head>

<body>

<form>

<input type="button" value="Start count!" onClick="doTimer()">

<input type="text" id="txt">

<input type="button" value="Stop count!" onclick="stopCount()">

</form>

</body>

</html>

LINK@KOREATECH 70

Javascript – Create Objects

 Create your own simple object personObj=new Object(); personObj.firstname="John"; personObj.lastname="Doe"; personObj.age=50; personObj.eyecolor="blue"; or personObj={firstname:"John", lastname:"Doe", age:50, eyecolor:"blue"}; //json object

 Create an object constructor function person (firstname, lastname, age, eyecolor) { this .firstname=firstname; this .lastname=lastname; this .age=age; this .eyecolor=eyecolor;

} var myFather= new person("John","Doe",50,"blue"); var myMother= new person("Sally","Rally",48,"green");

LINK@KOREATECH 71

Javascript – Create Objects

 Create your own object – 1/2

<html>

<head>

<script type="text/javascript"> function mycircle (x, y, r) { this .xcoord = x; this .ycoord = y; this .radius = r; this .retArea = getTheArea;

} this .retCirc = function () { return ( Math.PI * this.radius * 2 ); }; this .moveBy = moveCclBy;

} function getTheArea() { return ( Math.PI * this .radius * this .radius );

} function moveCclBy(xDis, yDis) { this .xcoord += xDis; this .ycoord += yDis;

LINK@KOREATECH 72

Javascript – Create Objects

 Create your own object – 2/2 function createObj() { var testcircle = new mycircle(3,4,5); testcircle.moveBy(2,3); window.alert( 'The area of the circle is ' + testcircle.retArea() ); window.alert( 'The circumference is ' + testcircle.retCirc() );

}

</script>

</head>

<body>

<input type="button" value="Creare Object" onclick="createObj()" />

</body>

</html>

LINK@KOREATECH 73

[Appendix] URL Encoding

 What is URL Encoding?

– the process of converting "a string" into "a valid URL format" by converting "prohibited characters" into "valid characters"

– URL encoding is normally performed to convert data passed via html forms, because such data may contain special character, such as "/",

".", "#", and so on

 What characters need to be encoded

– ASCII Control characters

• e.g.] carriage return (CR)  %0d

– Non-ASCII characters

• e.g.] 한국  %26%2354620%3B%26%2344397%3B

– Reserved characters

• e.g.] ampersand ("&")  %26

– Unsafe characters

• e.g.] 'Less Than' symbol ("<")  %3c

LINK@KOREATECH 74

[Appendix] URL Encoding

 Encoding of reserved and unsafe characters

LINK@KOREATECH 75

[Appendix] URL Encoding

 Example

– One of the most common encounters with URL Encoding is when dealing with <form>.

– Form methods (GET and POST) perform URL Encoding implicitly

<html><body>

<form method="GET" action="example.html">

<input type="text" name="var" size="50" value="This is a simple & short test.">

<input type="submit">

</form>

</body></html> http://link.koreatech.ac.kr/example.html?

var=This+is+a+simple+%26+short+test http://link.koreatech.ac.kr/example.html?

var=%24+%26+%3C+%3E+%3F+%3B+%23+

%3A+%3D+%2C+%22+%27+%7E+%2B+%25

LINK@KOREATECH 76

Download