JavaScript Asst. Prof. Dr. Kanda Saikaew (krunapon@kku.ac.th) - - PowerPoint PPT Presentation

javascript
SMART_READER_LITE
LIVE PREVIEW

JavaScript Asst. Prof. Dr. Kanda Saikaew (krunapon@kku.ac.th) - - PowerPoint PPT Presentation

JavaScript Asst. Prof. Dr. Kanda Saikaew (krunapon@kku.ac.th) Dept. of Computer Engineering Khon Kaen University 1 Why Learn JavaScript? JavaScript is used in millions of Web pages to Validate forms Detect browsers Create


slide-1
SLIDE 1

1

JavaScript

  • Asst. Prof. Dr. Kanda Saikaew

(krunapon@kku.ac.th)

  • Dept. of Computer Engineering

Khon Kaen University

slide-2
SLIDE 2

Why Learn JavaScript?

JavaScript is used in millions of Web

pages to

Validate forms Detect browsers Create cookies

JavaScript is the most popular

scripting language on the internet, and works in all major browsers

Internet Explorer Mozilla Firefox

2

slide-3
SLIDE 3

What is JavaScript?

JavaScript was designed to add

interactivity to HTML pages

A JavaScript is usually embedded

directly into HTML pages

JavaScript is an interpreted language

(means that scripts execute without preliminary compilation)

Everyone can use JavaScript without

purchasing a license

3

slide-4
SLIDE 4

What Can a JavaScript Do? (1/3)

JavaScrip

Script t gives HTML designers rs a program rammi ming tool

JavaScript is a scripting language with a

very simple syntax!

JavaScrip

Script t can put dynamic c text into an HTML page

- A JavaScript statement like this:

document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page

4

slide-5
SLIDE 5

What Can a JavaScript Do? (2/3)

 JavaSc

aScript ript can react to events

 A JavaScript can be set to execute when

something happens, like when a user clicks

  • n an HTML element

 JavaSc

aScrip ript t can read and write HTML elements ts

 A JavaScript can read and change the content

  • f an HTML element

 JavaSc

aScrip ript t can be used to validate te data

 A JavaScript can be used to validate form

data before it is submitted to a server

5

slide-6
SLIDE 6

What Can a JavaScript Do? (3/3)

JavaScrip

Script t can be used to detect ct the visito itor' r's 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

JavaScrip

Script t can be used to create te cookie ies

A JavaScript can be used to store and

retrieve information on the visitor's computer

6

slide-7
SLIDE 7

How to Put a JavaScript into an HTML Page

The HTML <script> tag is used to

insert a JavaScript into an HTML page

The word document.

t.wri write te is a standard JavaScript command for writing output to a page

Syntax

document.write(“type what you want to

write here”);

7

slide-8
SLIDE 8

Example: js1.html

<html> <body> <script type="text/javascript"> document.write("Hello World!"); </script> </body> </html>

8

slide-9
SLIDE 9

Where to Put the JavaScript (1/2)

Scrip

ipts ts in the head section

Scripts to be executed when they are

called, or when an event is triggered, go in the head section

When you place a script in the head

section, you will ensure that the script is loaded before anyone uses it

Example:

<html> <head> <script type="text/javascript"> .... </script> </head>

9

slide-10
SLIDE 10

Prompt Box Example

 Source code

<html> <head> <script type="text/javascript"> var text = prompt("Please enter text"); document.write("You have entered " + text); </script> </head> <body></body> </html>

10

 Output

slide-11
SLIDE 11

Functions

 Source code

<html> <head> <script type="text/javascript"> function displaymessage() { alert("Hello World!"); } </script> </head> <body> <form> <input type="button" value="Click me!"

  • nclick="displaymessage()" >

</form> </body> </html>

 Output

11

slide-12
SLIDE 12

for...in Statement

The for...in statement is used to loop

(iterate) through the elements of an array or through the properties of an

  • bject.

Syntax

tax for (variable in object) { code to be executed }

12

slide-13
SLIDE 13

for… in Sample

 Source code

<html> <body> <script type="text/javascript"> var x; var mycars = new Array(); mycars[0] = "Toyota"; mycars[1] = "Volvo"; mycars[2] = "BMW"; for (x in mycars) { document.write("<b>" + mycars[x] + "</b><br />"); } </script> </body> </html>

 Output

13

slide-14
SLIDE 14

Events

 By using JavaScript, we have the ability to

create dynamic web pages

 Events are actions that can be detected by

JavaScript.

 Every element on a web page has certain

events which can trigger JavaScript functions

 Events are normally used in combination

with functions, and the function will not be executed before the event occurs!

14

slide-15
SLIDE 15

Examples of Events

A mouse click A web page or an image loading Mousing over a hot spot on the web

page

Selecting an input box in an HTML

form

Submitting an HTML form A keystroke

15

slide-16
SLIDE 16
  • nClick Sample Code

 Source code

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

 Source code (cont.)

<body> <form> <input type="button" value="Start count!"

  • nClick="timedCount()">

<input type="text" id="txt"> </form> <p>Click on the button above. The input field will count for ever, starting at 0.</p> </body> </html>

16

slide-17
SLIDE 17
  • nClick Sample Output

17

setTimeout ( expression, timeout ); where expression is the JavaScript code to run after timeout milliseconds have elapsed.

slide-18
SLIDE 18
  • nload and onUnload

The onload and onUnload events are

triggered when the user enters or leaves the page

The onload event is often used to

check the visitor's browser type and browser version, and load the proper version of the web page based on the information

18

slide-19
SLIDE 19
  • nload Sample

 Source code

<html> <head> <script type="text/javascript"> function detectBrowser() { var browser=navigator.appName; var b_version=navigator.appVersion; var version=parseFloat(b_version); if ((browser=="Netscape" || browser=="Microsoft Internet Explorer") && (version>=4)) { alert("Your browser is good enough!"); } else { alert("It's time to upgrade your browser!"); } } </script></head> <body onload="detectBrowser()"/> </html>

 Output

19

slide-20
SLIDE 20
  • nFocus, onBlur and onChange

The onFocus, onBlur and onChange

events are often used in combination with validation of form fields.

Below is an example of how to use

the onChange event. The checkEmail() function will be called whenever the user changes the content of the field:

<input type="text" size="30" id="email"

  • nchange="checkEmail()">

20

slide-21
SLIDE 21
  • nChange Sample Code

<form name="go" onSubmit="return false;"> <select name="select"

  • nChange="window.document.location=window.docume

nt.go.select.value;"> <option value="#" selected>Please Select</option> <option value="http://www.microsoft.com">Microsoft</option> <option value="http://www.yahoo.com">Yahoo!</option> <option value="http://www.google.com">Google</option> </select> </form>

21

slide-22
SLIDE 22
  • nChange Sample Output

22

slide-23
SLIDE 23
  • nSubmit

 The onSubmit event is used to validate

ALL form fields before submitting it.

 Below is an example of how to use the

  • nSubmit event

 <form method="post" action="xxx.htm"

  • nsubmit="return checkForm()">

 The checkForm() function will be called

when the user clicks the submit button in the form

 If it returns true the form will be submitted,

  • therwise the submit will be cancelled

23

slide-24
SLIDE 24
  • nMouseOver and onMouseOut

 onMouseOver and onMouseOut are often

used to create "animated" buttons.

 Below is an example of an onMouseOver

  • event. An alert box appears when an
  • nMouseOver event is detected

 Example:

 <a href="http://www.w3schools.com"

  • nmouseover="alert('An onMouseOver event');return

false"> <img src="w3schools.gif" width="100" height="30"> </a>

24

slide-25
SLIDE 25
  • nMouseOver and onMouseOut Sample

 Source code

<html> <head> <script type="text/javascript"> function mouseOver() { document.b1.src ="b_blue.gif"; } function mouseOut() { document.b1.src ="b_pink.gif"; } </script> </head> <body> <a href="http://gear.kku.ac.th" target="_blank"> <img border="0" alt="Visit CoE KKU!" src="b_pink.gif" name="b1" width="26" height="26"

  • nmouseover="mouseOver()"
  • nmouseout="mouseOut()" /></a>

</body> </html>

 Output

25

slide-26
SLIDE 26

The try … catch Statement

The try … catch statement allows you

to test a block of code of errors

The try block contains the code to be

run

The catch block contains the code to be

executed if an error occurs

Syntax

try { // run some code here } catch (err) { // handle errors here }

26

slide-27
SLIDE 27

The try … catch Sample Code

 Source code

<html> <head> <script type="text/javascript"> var txt="" function message() { try { addalert("Welcome guest!"); } 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 home page.\n\n"; if(!confirm(txt)) { document.location.href="http://www. w3schools.com/"; } } }

 Source code (Cont.)

</script> </head> <body> <input type="button" value="View message" onclick="message()" /> </body> </html>

27

slide-28
SLIDE 28

The try… catch Sample Output

28

slide-29
SLIDE 29

The throw Statement

 The throw statement allows you to create an

exception

 If you use this statement together with the

try...catch statement

 You can control program flow and generate accurate

error messages.

 Synt

ntax ax

 throw(exception)  The exception can be a string, integer, Boolean or an

  • bject

 Note that throw is written in lowercase letters. Using

uppercase letters will generate a JavaScript error!

29

slide-30
SLIDE 30

The throw Sample Code

<html> <body> <script type="text/javascript"> var x=prompt("Enter a number between 0 and 10:",""); try { if(x>10) throw "Err1"; else if(x<0) throw "Err2"; } catch(er){ if(er=="Err1") alert("Error! The value is too high"); else if(er == "Err2") alert("Error! The value is too low"); } </script> </body> </html>

30

slide-31
SLIDE 31

The throw Sample Output

31

slide-32
SLIDE 32

JS Objects

JavaScript is an Object Oriented

Programming (OOP) language

An OOP language allows you to

define your own objects and make your own variable types.

Note that an object is just a special

kind of data

An object has properties and methods

32

slide-33
SLIDE 33

Object Properties

Properties are the values associated

with an object.

Sample Code

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

The output of the code above will be:

12

33

slide-34
SLIDE 34

Object Methods

Methods are the actions that can be

performed on objects.

Sample code

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

The output of the code above will be:

HELLO WORLD!

34

slide-35
SLIDE 35

JS Date Object

The Date object is used to work with

dates and times.

We define a Date object with the new

  • keyword. The following code line defines

a Date object called myDate:

var myDate=new Date() The Date object will automatically hold

the current date and time as its initial value!

35

slide-36
SLIDE 36

JS Date: Date()

 Source code

<html> <body> <script type="text/javascript" > document.write(Date()); </script> </body> </html>

 Output

36

slide-37
SLIDE 37

JS Date: getTime()

 Sample code

<html> <body> <script type="text/javascript"> var minutes = 1000*60; var hours = minutes*60; var days = hours*24; var years = days*365; var d = new Date(); var t = d.getTime(); var y = t/years; document.write("It's been: " + y + " years since 1970/01/01!"); </script> </body> </html>

 Output

37

slide-38
SLIDE 38

JS Date: setFullYear()

 Sample Code

<html> <body> <script type="text/javascript"> var d = new Date(); d.setFullYear(1992,2,26); document.write(d); </script> </body> </html>

 Output

38

slide-39
SLIDE 39

JS Date: getDay()

 Sample Code

<html> <body> <script type="text/javascript"> var d=new Date(); var weekday=new Array(7); weekday[0]="Sunday"; weekday[1]="Monday"; weekday[2]="Tuesday"; weekday[3]="Wednesday"; weekday[4]="Thursday"; weekday[5]="Friday"; weekday[6]="Saturday"; document.write("Today it is " + weekday[d.getDay()]); </script> </body> </html>

 Output

39

slide-40
SLIDE 40

JS Date: getHours, …

 Source code

<html> <head> <script type="text/javascript"> function startTime() { var today=new Date(); var h=today.getHours(); var m=today.getMinutes(); var s=today.getSeconds(); // add a zero in front of numbers<10 m=checkTime(m); s=checkTime(s); document.getElementById('txt').inner HTML=h+":"+m+":"+s; t=setTimeout('startTime()',500); }

 Source code (Cont.)

function checkTime(i) { if (i<10) { i="0" + i; } return i; } </script> </head> <body onload="startTime()"> <div id="txt"></div> </body> </html>

40

slide-41
SLIDE 41

JS Date: Output

41

slide-42
SLIDE 42

JS Array: Create Array

 Sample Code

<html> <body> <script type="text/javascript"> var mycars = new Array(); mycars[0] = "Toyota"; mycars[1] = "Volvo"; mycars[2] = "BMW"; for (i=0;i<mycars.length;i++) { document.write(mycars[i] + "<br />"); } </script> </body> </html>

 Output

42

slide-43
SLIDE 43

JS HTML DOM Document

The Document object represents the

entire HTML document

 It can be used to access all elements

in a page.

The Document object is part of the

Window object and is accessed through the window.document property

43

slide-44
SLIDE 44

Write Text to the Output

 Output  Source code

<html> <body> <script type="text/javascript"> document.write("Hello World!"); </script> </body> </html>

44

slide-45
SLIDE 45

Write Txt with Format to the Output

 Output  Source code

<html> <body> <script type="text/javascript"> document.write("<h1>This is a header</h1>"); </script> </body> </html>

45

slide-46
SLIDE 46

Return the Title of a Document

 Output

46

 Source code

<html> <head> <title>My title</title> </head> <body> The title of the document is: <script type="text/javascript"> document.write(document.title); </script> </body> </html>

slide-47
SLIDE 47

Use getElementById (1/2)

47

slide-48
SLIDE 48

Use getElementById (2/2)

<html><head> <script type="text/javascript"> function getValue() { var x=document.getElementById("myHeader"); alert(x.innerHTML); } </script></head> <body> <h1 id="myHeader" onclick="getValue()">This is a header</h1> <p>Click on the header to alert its value</p> </body> </html>

48

slide-49
SLIDE 49

Use getElementsByName (1/2)

<html> <head> <script type="text/javascript"> function getElements() { var x=document.getElements ByName("myInput"); alert(x.length); } </script> </head>

<body> <input name="myInput" type="text" size="20" /><br /> <input name="myInput" type="text" size="20" /><br /> <input name="myInput" type="text" size="20" /><br /> <br /> <input type="button"

  • nclick="getElements()"

value="How many elements named 'myInput'?" /> </body> </html>

49

slide-50
SLIDE 50

Use getElementsByName (2/2)

50

slide-51
SLIDE 51

Access Form Name (1/2)

<html> <body> <form id="Form1" name="Form1"> Your name: <input type="text"> </form> <form id="Form2" name="Form2"> Your car: <input type="text"> </form> <p> To access an item in a collection you can either use the number

  • r the name of the item:

</p> <script type="text/javascript"> document.write("<p>The first form's name is: " + document.forms[0].name + "</p>"); document.write("<p>The first form's name is: " + document.getElementById("Fo rm1").name + "</p>"); </script> </body> </html>

51

slide-52
SLIDE 52

Access Form Name (2/2)

52

slide-53
SLIDE 53

Form Validation (1/6)

Invalid Name

53

slide-54
SLIDE 54

Form Validation (2/6)

Invalid Age

54

slide-55
SLIDE 55

Form Validation (3/6)

Invalid Email

55

slide-56
SLIDE 56

Form Validation (4/6)

<html> <head> <script type="text/javascript"> function validate() { var at=document.getElementById("email").value.indexOf("@"); var age=document.getElementById("age").value; var fname=document.getElementById("fname").value; submitOK=true; if (fname.length>10) { alert("The name must be less than 10 characters"); submitOK=false; } if (isNaN(age) || age<1 || age>100) { alert("The age must be a number between 1 and 100"); submitOK=false; }

56

slide-57
SLIDE 57

Form Validation (5/6)

if (at==-1) { alert("Not a valid e-mail!"); submitOK=false; } if (submitOK) { document.write(""); window.location="http://localhost"; } } </script> </head> <body>

57

slide-58
SLIDE 58

Form Validation (6/6)

<form action="formValidate.html" onsubmit="validate()"> Name (max 10 chararcters): <input type="text" id="fname" size="20"><br /> Age (from 1 to 100): <input type="text" id="age" size="20"><br /> E-mail: <input type="text" id="email" size="20"><br /> <br /> <input type="submit" value="Submit"> </form> </body> </html>

58

slide-59
SLIDE 59

References

W3Schools, “JavaScript Tutorial”,

available at http://www.w3schools.com/js/default. asp

59