Transcript Slide 1

3.4 JavaScript
What is scripting
- Scripting languages are usually interpreted
programming languages
- Scripts are used on client side
 program to be run on client machine by
browser
- Scripts are used on server side
 program to be run on server with results
sent to browser
- use to add interactivity to web pages
1
JavaScript
- JavaScript คือ ภาษาประมวลผล (programming
language) ต่างจาก HTML ทีเ่ ป็นภาษาแสดงผล (markup
ื่ เดิมคือ LiveScript
language) ชอ
- เป็นโปรแกรมย่อยเล็ก ๆ ทีส
่ ามารถแทรกอยูใ่ นโค้ด HTML ได้
- ผลิตจากบริษ ัท Nestcape Communications ปี 2538
- โครงสร้างของ JavaScript ใกล้เคียงก ับภาษา Java เพราะ
ยึดโครงสร้างการพ ัฒนามาจากภาษา C เหมือนก ัน
- เป็นภาษาประเภทแปลไปทางานไป (Interpreter)
2
JavaScript
◊ some syntax is similar to Java
◊ much simpler – not fully Object-oriented
◊ case-sensitive
◊ weak types  Don’t have to declare types
use var for declare variables
(สามารถละ var ได้)
var greeting="hello"
var name ="alison"
greeting="hello"
name ="alison"
3
ตาแหน่งของการเขียน JavaScript
่ นห ัวของเอกสาร HTML
- ตาแหน่งสว
<head>
<script language=“javascript”>
…. คำสงั่ JavaScript……..
</script>
</head>
่ นต ัวของเอกสาร HTML
- ตาแหน่งสว
<body>
…. Tag คำสงั่ HTML……..
<script language=“javascript”>
…. คำสงั่ JavaScript……..
</script>
…. Tag คำสงั่ HTML……..
</body>
4
ตาแหน่งของการเขียน JavaScript
- เป็นค่า event ของแท็กคาสง่ ั HTML
<body onload=“alert(‘Hello! Boy.’)” onunload=“alert(‘Goodbye!’)”>
- เก็บไว้ในไฟล์แยกต่างหาก โดยมีนามสกุล .js
<script language=“javascript” src=“unit1.js”>
</script>
5
Examples of JavaScript
- simply embedded in web page, between
script tags
- // or /* */ are comments of JavaScript
<h1> JavaScript Example 1 </h1>
<script type=“text/javascript”>
//<script language=“javascript”>
document.writeln(“Hello World”)
</script>
6
Input JavaScript
- get input from user by simple dialogue box
(alert, confirm, prompt command)
<script type=“text/javascript”>
<!-window.alert(“Welcome to\nJavaScript\nProgramming” )
// -->
</script>
7
<script type=“text/javascript”>
<!-var aname = window.prompt(“What is your name?”, “” )
document.writeln(“<p>Hello ”+aname+“.”)
document.writeln(“I hope you like web page</p>”)
if (confirm(“That’s right”))
alert (“Finish”)
else
alert (“Refresh again”)
// -->
</script>
8
Expression
Numeric Expressions
+ , - , * , / , %, ++, --=, +-, *= , /=, %=
Logical Expressions
&& , || , ! , ==, != , > , < , >= , <=
9
Example
<html>
<head><title>math operation</title></head>
<body>
<script type=“text/javascript”>
<!-var s,n1,n2,n3;
s = window.prompt(“Enter number1:”);
n1 = parseInt(s);
s = window.prompt(“Enter number2:”);
n2 = parseInt(s);
n3 = n1+n2;
document.writeln(“result= ” + n3);
//-->
</script>
</body>
</html>
10
JavaScript Conditionals and Loops
Condition
var vname = prompt("What is your name?”, "")
if (vname=="John") document.writlen("Hello.")
else if (vname=="Jean")
document.writeln("Bonjour.")
else document.writeln("Who are you?")
var choice = prompt(“Select 1, 2,3 or 4”, "");
switch (choice) {
case “1”: case “2” : alert(“Hi”);
break;
case “3” : alert(“Bye”);
break;
case “4” : alert(“Great”);
break;
default : alert(“False”); }
11
Example
<html>
<head><title>switch statement</title></head>
<body><script type="text/javascript">
<!-var choice, colorTag;
choice = window.prompt("Select text color:\n"+ "1.red, 2.green, 3.blue","1");
switch (choice){
case "1": colorTag = "color = \"red\""; break;
case "2": colorTag = "color = \"green\""; break;
case "3": colorTag = "color = \"blue\""; break;
default : colorTag = "color = \"black\""; break;
}
document.write("<font "+colorTag+"><b>Hello</b></font>");
//-->
</script>
</body></html>
12
Loop
var counter;
for(counter=1; counter<=10; counter++)
{
document.writeln("<p> Value: " + counter + "</p">);
}
var counter=0;
do {
counter++;
document.writeln("<p> Value: " + counter + "</p">);
} while(counter <10);
var counter=0;
while (counter<10) {
counter++;
document.writeln("<p> Value: " + counter + "</p">);
}
13
Example
<html>
<head><title>do while statement</title></head>
<body>
<script type="text/javascript">
<!-var counter=1;
do {
document.write("<h" + counter + ">This is an " + counter +
" level head</h"+counter+">");
++counter;
} while(counter<=6)
//-->
</script>
</body>
</html>
14
Result of Example
15
JavaScript functions
are easily defined
 Usually placed in script in head of document,
and called from body
<head>
<script language=javascript>
function greet(aname)
{ document.writeln(“Hello ” + aname) }
</script>
</head>
<body>
<script type=text/javascript>
var yourname = prompt("What is your name”,“”)
greet(yourname) //javascript:greet(yourname)
</script>
16
Programmer-defined functions
all variables declared in function are local
variables
<head>
<script language=javascript>
function square(y)
{ return y*y; }
</script>
</head>
<body>
<script language=javascript>
var num = prompt("What is number”,“0”)
alert(“Result is”+square(num))
</script>
17
Arrays
Declaration 1-dimensional
var n = new Array(5);
or
var n =[10, 20, 30, 40, 50];
or
var n = new Array(10, 20, 30 ,40, 50);
Declaration two-dimensional
var b = new Array(2);
var b[0]=new Array(3);
var b[1]=new Array(5);
b[0][1] = 5;
18
More Declaration two-dimensional
var b = [ [1,2,3], [3,4,5] ];
var array1 = [[6,4],
[2],
[9,5,3]];
Arrays method
Method sort()
uses string comparisons to determine
the sorting order of the Array elements.
19
example sort method
<html>
<head>
<title>Sorting an Array with Array Method sort</title>
<script type = "text/javascript">
function start()
{ var a = [ "f", "r", "u", "w", "z", "B", "G", "e", "P", "q" ];
document.writeln( "<h1>Sorting an Array</h1>" );
outputArray( "Data items in original order: ", a );
a.sort(); // sort the array
outputArray( "Data items in ascending order: ", a );
}
function outputArray( header, theArray )
{ document.writeln( "<p>" + header +
theArray.join( " " ) + "</p>" );
}
</script>
</head><body onload = "start()"></body>
</html>
20
JavaScript Object
-
Math Object
String Object
Date Object
Boolean and Number Object
Window Object
Document Object
21
Math object
Math.abs(x)
absolute value of x
Math.ceil(x)
round x to the smallest integer not less than x
Math.floor(x)
round x to the largest integer not greater than x
Math.cos(x)
cosine of x ( x in radians)
Math.exp(x)
exponential method ex
Math.log(x)
natural logarithm of x (base e)
Math.sqrt(x)
square root of x
22
Math object
Math.max(x1,x2)
find maximum between x1 and x2
Math.min(x1,x2)
find minimum between x1 and x2
Math.random()
generate floating-point number between
[0.0, 1.0]
Math.round(x)
rounds x to the closest integer
Math.pow(x,y)
calculates the value of x raised to the yth
power
more on :- http://www.w3schools.com/js/default.asp
23
String object
charAt(index)
charCodeAt(index)
fromCharCode(ascii,ascii,…,ascii)
indexOf(substring, index)
lastIndexOf(substring,index)
slice(start,end)
substring(start,length)
toLowerCase()
toUpperCase()
toString()
valueOf()
24
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Character Processing Methods</title>
<script type = "text/javascript">
var s = "ZEBRA";
var s2 = "AbCdEfG";
document.writeln( "<p>Character at index 0 in ' " +
s + " ' is " + s.charAt( 0 ) );
document.writeln( "<br />Character code at index 0 in ' "
+ s + " ' is " + s.charCodeAt( 0 ) + "</p>" );
document.writeln( "<p>' " +
String.fromCharCode( 87, 79, 82, 68 ) +
" ' contains character codes 87, 79, 82 and 68</p>" )
document.writeln( "<p>'" + s2 + "' in lowercase is '" +
s2.toLowerCase() + "'" );
document.writeln( "<br />'" + s2 + "' in uppercase is '"
+ s2.toUpperCase() + "'</p>" );
</script>
</head>
</html>
25
Date object
getDate()
getDay()
getFullYear()
getHour()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
setDate(val)
setTime(ms)
setMonth(m,d)
setHours(h,m,s,ms)
26
Window object
open(url, name,options)
prompt(prompt,default)
close()
focus()
blur()
27
Document Object Model (DOM)
Window
Frame
Document
Location
History
Screen
Navigator
Document
Document
Textarea
Layer
Text
Link
FileUpload
Image
Password
Area
Hidden
Anchor
Submit
Applet
Reset
Form
Radio
Plugin
Checkbox
Plugin
MimeType
Button
Select
Option
28
Document Objects
 Using JavaScript can access and modify many
of the “objects” in a document.
Object
Window
Location
History
Screen
Navigator
Document
ความหมาย
ั้
เป็น object ชนบนสุ
ด เป็นต ัวแทนของหน้าต่าง browser
เป็น object ทีใ่ ชเ้ ก็บข้อมูลตาแหน่งของเว็บปัจจุบ ันทีเ่ รา
เปิ ดอยู่
เป็น object ทีเ่ ก็บการเข้าเยีย
่ มชมเว็บในอดีต
่
เป็น object ทีเ่ ก็บข้อมูลของหน้าจอแสดงผล เชน
ี ใี่ ช ้
ความกว้างยาวของหน้าจอ ค่าความละเอียดของสท
ั
เป็น object ทีเ่ ก็บข้อมูลของต ัว browser เลขทีเ่ วอร์ชน
เป็น object ทีเ่ ป็นต ัวแทนเอกสาร html ทีเ่ ปิ ดอยู่
29
Object
- JavaScript จะอ้างอิง object ของ HTML เพือ
่ ให้นาค่าที่
ได้จากการประมวลผลมาแสดงทาง object ของ HTML
- การอ้าง HTML DOM จะอ้างผ่านโครงสร้างข้างต้น โดยเริม
่
จาก window ซงึ่ เป็น object ต ัวแรกทีแ
่ สดงผ่าน browser
แล้วจึงไล่เรียงมาตามโครงสร้าง จนถึงต ัวทีต
่ อ
้ งการ
่ window.document.image[7]
เชน
window.document.forms[0].text[3]
- แต่ในการใชง้ านจริง สามารถละ window ได้
่ document.image[7]
เชน
document.forms[0].text[3]
30
Property of Object
่ ความกว้าง
- Property คือ คุณสมบ ัติของ object เชน
ความสูง ส ี ขนาดต ัวอ ักษร เป็นต้น
- สามารถแก้ไขค่าของคุณสมบ ัติเหล่านีไ้ ด้
่ document.bgColor = “#ffaa88”;
เชน
document.forms[0].text[4].value = “Hello!”;
- สามารถเก็บค่าของคุณสมบ ัติไว้ในต ัวแปรได้
่
เชน
x= document.bgColor
Y = document.forms[0].text[4].value
31
Method of Object
- Method คือ งานย่อยที่ object สามารถทาได้ เป็นงานหรือ
การกระทาทีก
่ าหนดไว้ในต ัว object อยูแ
่ ล้ว
่ document.write(“This is my text.”)
เชน
document.forms[0].text[4].focus()
- method และ property จะต่างก ันตรงที่ method จะมี ()
แต่ property ไม่ม ี
32
Referencing to the document objects
- การอ้างอิงแบบเต็ม
ั
เป็นการอ้างอิงทีม
่ ค
ี วามชดเจนแน่
นอน เพราะไล่ตงแต่
ั้
object ใหญ่ ไปจนถึง object ย่อยทีต
่ อ
้ งการ ทาให้ทราบ
ทีม
่ าของ object ว่าอยูภ
่ ายใต้โครงสร้างต ัวใด
่ document.images[0].src=“new.gif”
เชน
document.forms[0].text[0].value=“hello”
33
Referencing to the document objects
 Each object has properties allowing us to access
the lower level objects in the hierarchy.
e.g., document.forms returns an array of forms
in the document.
 Normally an array of objects is returned, and we
access a specific one (e.g., first form) using array
subscripting.
document.forms[0]
 We can access the input elements using
"elements":
document.forms[0].elements[0]
34
forms.elements example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Form Changes</title>
<script type = "text/javascript">
function show(n)
{ alert(document.forms[0].elements[n].value) }
</script>
</head>
<body>
<h1> Form Changes</h1>
<form name=“form1” action=“”>
<p> A text box <input type=“text” name=“t1” value=“new text”/>
</p>
<p> <textarea name=“area1” rows=“10” cols=“40”>some text
</textarea> </p>
<p>
<input type=“button” onclick=“show(0)” value=“show 0” />
<input type=“button” onclick=“show(1)” value=“show 1” />
</p> </form>
</body>
35
</html>
if press button “show 0”
if press button “show 1”
36
Referencing to the document objects
- การอ้างอิงโดยใช ้ name/id
ื่ ให้ object เพือ
id ย่อมาจาก index เป็นการกาหนดชอ
่ ใช ้
ในการอ้างถึง
่
เชน
<form id=“myform" ….>
<input type="text" name=“mytext" …>
</form>
document.myform.mytext.value=“hello”
ั้
สามารถทาให้การอ้างสนลง
โดยใช ้ getElementById
่
เชน
document.getElementById(“mytext”).value=“hello”
37
Referencing to the document objects
- การอ้างอิงโดยใช ้ this
้ า้ งอิง object ต ัวที่ JavaScript ฝัง
this เป็นคาสงวน ใชอ
ต ัวอยู่ ใชใ้ นกรณีท ี่ script เก็บอยูใ่ นต ัว object ด ังนน
ั้
เวลาอ้างถึงต ัวเอง จะใช ้ this
่
เชน
<font color=“blue”
onmouseover=“this.style.color=‘red’”
onmouseout=“this.style.color=‘blue’”>
ข้อความ
</font>
ถ้าใช ้ id
<font id=“text” color=“blue”
onmouseover=“text.style.color=‘red’”
onmouseout=“text.style.color=‘blue’”>
ข้อความ
</font>
38
Referencing to the document objects
-การใช ้ JavaScript อ้างอิงคุณสมบ ัติ CSS
JavaScript สามารถอ้างอิงคุณสมบ ัติ CSS ได้โดยผ่าน
object ของ HTML ด ังนี้
document.getElementById(“object name”).style.property=“value”
่
เชน
document.getElementById(“text1”).style.backgroundColor=“red”
document.getElementById(“text2”).style.textDecoration=“underline”
39
Referencing to the document objects
ั
ื่ ของ property จะเปลีย
สงิ่ ทีน
่ า
่ สงเกตคื
อ ชอ
่ นไป
่ background-color ใน CSS จะเปลีย
เชน
่ นเป็น
backgroundColor ใน JavaScript โดยขีดกลางจะหายไป และ
C กลายเป็นต ัวใหญ่แทน
ื่ property
ต ัวอย่างเปรียบเทียบชอ
CSS
background
background-color
boder-bottom
font-size
margin-left
JavaScript
background
backgroundColor
borderBottom
fontSize
marginLeft
40
Event Handlers
- For JavaScript, using dialogue boxes (e.g.,
prompt) for user input, and different ways to
modify the page
- As well as using dialogue boxes for user input,
we can detect when certain events happen, and
act on these: e.g, mouse clicks and movement,
form submission, key presses
41
Event Handlers
 You can specify what action to take if
various events happen
 We can add attribute to relevant HTML
element specifying JavaScript method to
call
<input type=“button” value=“press”
onclick=“javascript:clickfn()”>
42
Event Handlers
 Each type of document object has a set of
possible event handlers which can be
defined. E.g., button has "onclick"
example
43
<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01//EN"
"http://www/w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Don't Click Me</title>
<script type="text/javascript">
function dontclickme() {
alert("I told you not to click me"); }
</script>
</head>
<body>
<form action="">
<p>
<input type="button" value="Don't do it!"
onclick="dontclickme()"/>
</p>
</form>
</body>
</html>
44
2.5 DHTML
 DHTML = Dynamic HTML
 Use JavaScript to dynamically change
objects on web page:
position of objects
content of objects
properties of objects (e.g., color)
 Will show here how it can be used to create
simple animation.
 This requires that we can specify, and
change position of objects.
45
Positioning objects
 One way to position objects in HTML
is using CSS-P (CSS positioning).
 We create sections (divisions) in our HTML,
which will have a position and size on
screen.
 We use CSS to specify the position and size.
46
The DIV element
 The DIV element is used to specify sections of HTML we want
to be able to position:
<div id=“mybit”>
<h1> My Page </h1>
<img src=“alison.gif”/>
<p> Isn’t it great </p>
</div>
 We give the section an id - a bit like a name.
47
Adding style
 We can specify a CSS rule for just that
section, using its id:
<style type=“text/css”>
#mybit {color: blue; position: relative;
pixelLeft: 50}
</style>
position: relative states that it should
be relative to other elements on page.
pixelLeft gives distance from left in
pixels
48
Making it move
 We can modify stylesheet property
values from within JavaScript:
mybit.style.pixelLeft = 300;
mybit.style.color = “red”;
 Could have a function that changed
position of section:
function jump() {
mybit.style.pixelLeft += 20;
}
 Then could have: onclick=“jump()”
49
Jump Example
In head
In body
<script type=“text/javascript”>
function jump() {
mybit.style.pixelLeft += 20;
}
</script>
…
<div id=“mybit”>
<h1> Hello </h1>
</div>
<form>
<input type=“button” value=“Jump”
onclick=“jump()”>
</form>
50
Moving across the screen
 We can keep adding a little to the
positions, until it has moved enough..
function move() {
if(mybit.style.pixelLeft < 300)
{
mybit.style.pixelLeft +=5;
setTimeout(“move()”, 50);
}
 setTimeout calls function again after
small time delay.
51
DHTML : summary
 Can manipulate position and properties
of bits of HTML using JavaScript.
 One way is to use CSS to specify
position of section of HTML, and then
change the position under JavaScript.
52
การบ้าน
่ สาหร ับ
ให้หาว่ามี Events อะไรบ้าง โดยแยกตามกลุม
่ เชน
mouse, keyboard, frame, form พร้อมทงบอกความหมาย
ั้
่
เชน
Events สาหร ับ mouse
onclick: เกิดเหตุการณ์นเี้ มือ
่ มีการคลิกที่ tag หรือ object
onmouseover: เกิดเหตุการณ์นเี้ มือ
่ ต ัวชเี้ มาสเ์ ลือ
่ นมาอยูบ
่ น
tag หรือ object
53