1
JavaScript
- Asst. Prof. Dr. Kanda Saikaew
(krunapon@kku.ac.th)
- Dept. of Computer Engineering
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
1
JavaScript is used in millions of Web
Validate forms Detect browsers Create cookies
JavaScript is the most popular
Internet Explorer Mozilla Firefox
2
JavaScript was designed to add
A JavaScript is usually embedded
JavaScript is an interpreted language
Everyone can use JavaScript without
3
JavaScrip
JavaScript is a scripting language with a
JavaScrip
- A JavaScript statement like this:
4
JavaSc
A JavaScript can be set to execute when
something happens, like when a user clicks
JavaSc
A JavaScript can read and change the content
JavaSc
A JavaScript can be used to validate form
data before it is submitted to a server
5
JavaScrip
A JavaScript can be used to detect the
JavaScrip
A JavaScript can be used to store and
6
The HTML <script> tag is used to
The word document.
Syntax
document.write(“type what you want to
7
8
Scrip
Scripts to be executed when they are
When you place a script in the head
Example:
9
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
Source code
<html> <head> <script type="text/javascript"> function displaymessage() { alert("Hello World!"); } </script> </head> <body> <form> <input type="button" value="Click me!"
</form> </body> </html>
Output
11
The for...in statement is used to loop
Syntax
12
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
By using JavaScript, we have the ability to
Events are actions that can be detected by
Every element on a web page has certain
Events are normally used in combination
14
A mouse click A web page or an image loading Mousing over a hot spot on the web
Selecting an input box in an HTML
Submitting an HTML form A keystroke
15
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!"
<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
17
setTimeout ( expression, timeout ); where expression is the JavaScript code to run after timeout milliseconds have elapsed.
The onload and onUnload events are
The onload event is often used to
18
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
The onFocus, onBlur and onChange
Below is an example of how to use
<input type="text" size="30" id="email"
20
<form name="go" onSubmit="return false;"> <select name="select"
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
22
The onSubmit event is used to validate
Below is an example of how to use the
<form method="post" action="xxx.htm"
The checkForm() function will be called
If it returns true the form will be submitted,
23
onMouseOver and onMouseOut are often
Below is an example of an onMouseOver
Example:
<a href="http://www.w3schools.com"
false"> <img src="w3schools.gif" width="100" height="30"> </a>
24
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"
</body> </html>
Output
25
The try … catch statement allows you
The try block contains the code to be
The catch block contains the code to be
Syntax
26
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
28
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
Note that throw is written in lowercase letters. Using
uppercase letters will generate a JavaScript error!
29
<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
31
JavaScript is an Object Oriented
An OOP language allows you to
Note that an object is just a special
An object has properties and methods
32
Properties are the values associated
Sample Code
The output of the code above will be:
33
Methods are the actions that can be
Sample code
The output of the code above will be:
34
The Date object is used to work with
We define a Date object with the new
var myDate=new Date() The Date object will automatically hold
35
Source code
<html> <body> <script type="text/javascript" > document.write(Date()); </script> </body> </html>
Output
36
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
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
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
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
41
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
The Document object represents the
It can be used to access all elements
The Document object is part of the
43
Output Source code
<html> <body> <script type="text/javascript"> document.write("Hello World!"); </script> </body> </html>
44
Output Source code
<html> <body> <script type="text/javascript"> document.write("<h1>This is a header</h1>"); </script> </body> </html>
45
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>
47
<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
<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"
value="How many elements named 'myInput'?" /> </body> </html>
49
50
<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
</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
52
Invalid Name
53
Invalid Age
54
Invalid Email
55
<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
if (at==-1) { alert("Not a valid e-mail!"); submitOK=false; } if (submitOK) { document.write(""); window.location="http://localhost"; } } </script> </head> <body>
57
<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
W3Schools, “JavaScript Tutorial”,
59