Post on 11-Jan-2016
© Minder Chen, 1998-2002 JavaScript Example - 1
Learning JavaScript By Examples
byMinder Chen
mchen@gmu.eduhttp://65.168.115.5/dhtml/javascript/
© Minder Chen, 1998-2002 JavaScript Example - 2
Introduction to Programming• Internal data structures: Store in main memory; data
exist during the execution of the program– Simple data types
• Integer• Character• String• Real• Currency
– Indexed Array: A(1), A(2)– Associate Array: A("key") – Record: student.id, student.name, student.address– List: Add to a list, remove from a list, retrieve from a list – Tree: Hierarchical data structure; traverse the tree
• External data structure: store in disk drives; persistence– Document: HTML and XML– File: Sequential, Indexed, Index-sequential – Database: Relational or object-oriented databases
Programming =
Data Structures
+
Algorithm
© Minder Chen, 1998-2002 JavaScript Example - 3
Algorithm• Basic constructs:
– Constant: 123, "Hello"– Variables: Age, InterestRate– Operators
• Mathematical operators: +, -, *, /– Expression: Principal * InterestRate– Statements
• Data declarations: Dim Age as Integer• Statement:
– X= X + 1 // assignment statement– I = P * R + fx(2, y) // Function call– TempConvert(40, F) // Subroutine– Document.write("Hello World") // Input/output statement
• Invoking procedures: TempConvert( F, C) • Control statements
– Sequential, S1; S2; – Decision: If X=Y Then S1 Else S2; – Loop: Do S1; S2 10 times
• Software modules: – Subroutine or Function/Procedure– Class: instanceOfaClass.method()– Event Handling Procedures: OnClick="…."
3X:
X=Y
S1 S2
True False
TempConvert(32, X)
TempConvert(F, C)
F C
© Minder Chen, 1998-2002 JavaScript Example - 4
hello_world.htm<html><head><title>Hello World!</title></head><body><script language="JavaScript"><!--document.write("<h1>Write to the browser</h1>")document.write("Hello World")// --></script></body></html>
document is an object. Write( ) is a method associated with document. It allows you to write text to an HTML document that is currently displayed in a browser.
document is an object. Write( ) is a method associated with document. It allows you to write text to an HTML document that is currently displayed in a browser.
© Minder Chen, 1998-2002 JavaScript Example - 5
alert.htm<html>
<head>
<title> Alert() </title>
</head>
<body>
alert('You clicked the button')
<form>
<input type="button" value="Alert"
onClick="alert('You clicked the button')">
</form>
</body></html>
• onClick is an event associated with the button. • alert( ) is a build-in function.
• onClick is an event associated with the button. • alert( ) is a build-in function.
© Minder Chen, 1998-2002 JavaScript Example - 6
function_square.htm: function call<html><head><script LANGUAGE="JavaScript"><!-- to hide script contents from old browsers function square(i) { // document.write("The call passed ", i ," to the function.","<BR>") return i * i }// end hiding contents from old browsers --></script><title></title></head><body><script> document.write("The function square() returned ",square(5),".")</script><br>All done. </body></html>
The call passed 5 to the function.The function square() returned 25. All done.
© Minder Chen, 1998-2002 JavaScript Example - 7
Debug the code• IE 5.0; Choose
Tools > Internet Options > Advanced
• Deselect "Disable script debugging"
• Select "Display a notification about every script error"
© Minder Chen, 1998-2002 JavaScript Example - 8
© Minder Chen, 1998-2002 JavaScript Example - 9
File.htm: Include JavaScript Source Code
file.htm<html><head><title>Include File</title></head><body>
<script src="file.js"></script></body></html>
file.jsdocument.write("Hello world!")document.write("from an include file.js file")
© Minder Chen, 1998-2002 JavaScript Example - 10
prompt.htm<html><head><title> Prompt() </title></head><script language="JavaScript">function on_prompt(){var ans ans = prompt("What is your name?", "Enter Your Name Here"); document.write("Hello " + ans + "!") }</script><body><script>on_prompt();</script></body></html>
Hello Minder Chen!
• on_prompt( ) is a user-defined function. • on_prompt( ) is a user-defined function.
© Minder Chen, 1998-2002 JavaScript Example - 11
status.htm: onMouseOver and onMouseOut Events <html><head><title>Event</title></head><body>Use onMouseOver event of a hypertext link element to display text at
Browser window's status bar. <br>
<a href="http://www.erols.com/aitc" onMouseOver="window.status='Visit AITC web site'; return true"
onMouseOut="window.status='Done'; return true"> AITC </a>
</body></html>
Browser window's status bar
return true JavaScript checks to see if there is a status bar; it finds one and reports back that the text can be placed. You have to play by JavaScript rules to get this effect.
Ref: http://www.htmlgoodies.com/beyond/adv_js.html
© Minder Chen, 1998-2002 JavaScript Example - 12
Reference HTML Elements
Hello_button.htmHello_button.htm<html><head></head><body><form name="form1">Message: <input type="text" name="text1"> <input type="button" value="Say Hello" onClick="window.document.form1.text1.value='Hello World' "> </form></body></html>
window
document
form
text button
© Minder Chen, 1998-2002 JavaScript Example - 13
Building Interactive Applications<HTML><HEAD><SCRIPT LANGUAGE="JavaScript"><!-- Beginning of JavaScript -function MsgBox (textstring) {
alert (textstring) }// - End of JavaScript - --></SCRIPT></HEAD> <BODY> <FORM>
<INPUT NAME="text1" TYPE=Text><INPUT NAME="submit" TYPE=Button VALUE="Show Me" onClick="MsgBox(this.form.text1.value)">
</FORM></BODY></HTML>
© Minder Chen, 1998-2002 JavaScript Example - 14
scope_variable.htm: Scope of Variables<html><head><title> Scope of Variables </title></head><script language="JavaScript">var gv1 = "10 global"; gv2 = "20 global"; function test(){var lv1="5 local"; var gv1 = "10 local redefined";document.write("into the function<br>"); document.write("gv1=", gv1, "<br>"); document.write("gv2=", gv2, "<br>"); document.write("lv1=", lv1, "<br>");document.write("out of the function<br>"); }</script><body><script>document.write("into the global<br>"); document.write("gv1=", gv1, "<br>"); document.write("gv2=", gv2, "<br>"); test();document.write("out of the global<br>"); </script></body></html>
into the globalgv1=10 globalgv2=20 globalinto the functiongv1=10 local redefinedgv2=20 globallv1=5 localout of the functionout of the global
© Minder Chen, 1998-2002 JavaScript Example - 15
Document Object Model
• <form name="formName" …>– document.forms[0], document.forms[1], ..– document.formName– document.formName.elements[index]– document.formName.formElementName– document.formName.formElementName.property
© Minder Chen, 1998-2002 JavaScript Example - 16
add2.htm<html><head><title>Add Two Number</title></head><body><script language="JavaScript">function calculate(myForm)function calculate(myForm){ { var i; var i; i = parseInt(myForm.T1.value) + parseInt(myForm.T2.value);i = parseInt(myForm.T1.value) + parseInt(myForm.T2.value);myForm.T3.value = i; myForm.T3.value = i; }}</script></script><form name="form1"> <p>a = <input TYPE="text" SIZE="20" NAME="T1"> </p> <p>b = <input TYPE="text" SIZE="20" NAME="T2"> </p> <p>a + b = <input TYPE="text" SIZE="20" NAME="T3"> </p> <p><input LANGUAGE="JavaScript" TYPE="button" VALUE="Calculate" ONCLICK="calculate(this.form)"></p></form></body></html>
• thisthis refers to whatever object contains the script in which the keywords is used. • In this script, this this refers to the calculate button. • this.formthis.form refers to the form that contains the form element object.
• thisthis refers to whatever object contains the script in which the keywords is used. • In this script, this this refers to the calculate button. • this.formthis.form refers to the form that contains the form element object.
© Minder Chen, 1998-2002 JavaScript Example - 17
cal.htm<html><head><title>Calculations</title></head><body>
<form onSubmit = "document.forms[0].elements[1].value =
Math.round(document.forms[0].elements[0].value/2.2*100)/100;
return false;">
How many pounds? <input size="10" value="10" id="lb"> <br>
Kilogram (Kg)? <input size="10" id="kg"> <p>
<input type="submit" value="calculate">
</form>
<a href="#" onMouseOver="alert('Hi there!');">Move mouse over me!</a>
</body>
</html>
© Minder Chen, 1998-2002 JavaScript Example - 18
calculator2.htm
<html><head><title>Calculate Two Numbers</title></head><body><script LANGUAGE="JavaScript"><!--function calculate(myForm){var a, b, result, error_msg; var op = myForm.D1.valuea = parseInt(myForm.T1.value) b = parseInt(myForm.T2.value)error_msg = ""if (isNaN(a)) {
error_msg = error_msg + "a=" + myForm.T1.value + " is not a number \n"} if (isNaN(b)) {
error_msg = error_msg + "b=" + myForm.T2.value + " is not a number \n"}
© Minder Chen, 1998-2002 JavaScript Example - 19
calculator2.htm (continued)if (error_msg=="") {
switch (op){case "+":
result = a + bbreak
case "-":result = a - bbreak
case "*":result = a * bbreak
case "/":result = a / bbreak
}myForm.T3.value = result
} else{
alert(error_msg)}}// --></script>
© Minder Chen, 1998-2002 JavaScript Example - 20
calculator2.htm (continued)<form NAME="form1"> <p>a = <input TYPE="text" SIZE="20" NAME="T1"> </p> <p><select SIZE="1" NAME="D1"> <option selected value="+"> + </option> <option value="-"> - </option> <option value="*"> * </option> <option value="/"> / </option> </select> <p>b = <input TYPE="text" SIZE="20" NAME="T2"> <p>result = <input TYPE="text" SIZE="20" NAME="T3">
<p><input LANGUAGE="JavaScript" TYPE="button" VALUE="Calculate"
ONCLICK="calculate(document.form1);" NAME="B1"> </p></form></body></html>
© Minder Chen, 1998-2002 JavaScript Example - 21
telltime.htm<SCRIPT LANGUAGE="JavaScript">
<!--
// These next lines of code execute when the script tag is parsed.
var d = new Date()
var h = d.getHours()
if (h < 12)
document.write("Good morning!")
else
if (h < 17)
document.write("Good afternoon!")
else
document.write("Good evening!")
document.write("<br><br>Welcome to the world of JScript. ")
document.write("<br>Just in case you were wondering, <br>It's " + d + ".")
//-->
</SCRIPT>
Good evening!
Welcome to the world of JScript. Just in case you were wondering, It's Thu Jul 15 21:21:49 EDT 1999.
© Minder Chen, 1998-2002 JavaScript Example - 22
JavaScript: Looping<html><head><title>For Loop</title></head><body>
<p><strong>Looping example:</strong></p><script LANGUAGE="JavaScript">var i, total total = 0 for (i = 1; i<=10; i++) { document.write("i = " + i + "<BR>")total = total + i
} document.write("total = " + total + "<BR>")</script></body></html>
Looping example:
i = 1i = 2i = 3i = 4i = 5i = 6i = 7i = 8i = 9i = 10total = 55
© Minder Chen, 1998-2002 JavaScript Example - 23
write.htm<html><head><title> Document.write </title></head><script language="JavaScript"> document.write("<h1>Client-side JavaScript</h1>"); for(i = 1; i<=10; i++) {
document.write(i + "<sup>2</sup> = " + i*i + "<br>"); } </script><body></body></html>
© Minder Chen, 1998-2002 JavaScript Example - 24
Looping and Array<html><head><title>For Loop and Array</title></head><body><h1>Looping and Array</h1><script language="JavaScript"> var i, totalvar x = new Array(66, 77, 88, 99, 55)total = 0 document.write("<pre>i\tx[i]\n"); document.write("=\t====\n"); for (i=0; i<=3; i++) {
document.write(i+ "\t" + x[i] + "\n"); }document.write("\n\n</pre>"); for (i=0; i< x.length; i++) {
document.write(" i= " + i + " " + "x[" + i + "]=" + x[i] + "<br>");
total = total + x[i]; } document.write("Total = " + total + "<BR>"); </script></body></html>
© Minder Chen, 1998-2002 JavaScript Example - 25
Multiplication Table: loop2.htm<html>
<head><title>For Loop</title></head>
<body>
<p><strong>Multiplication table:
</strong></p>
<script LANGUAGE="JavaScript">
var i, j
document.write("<table style={font-size=70%} border=3>")
for (i = 1; i<=12; i++)
{
document.write("<tr>")
for (j = 1; j<=12; j++)
{
document.write("<td>" + i + "*" + j + "= " + i*j + "</td>")
}
document.write("</tr>")
}
document.write("</table>")
</script></body></html>
© Minder Chen, 1998-2002 JavaScript Example - 26
formElement. Focus• How do I make automatically place the cursor in a certain
form field?• The Situtation: You have created a form that always
requires the user to begin filling in at specific point. But your users must manually click the box before typing.
<html><head></head><body onLoad = "document.x.b.focus()"> <form name="x"> <input type="text" name="a" value="Default"><input type="text" name="b"><input type="submit"></form></body></html>
© Minder Chen, 1998-2002 JavaScript Example - 27
validate_form_2.htm: Form Input Data Validation<html><head><script LANGUAGE="JavaScript">function checkNum(str, min, max) { if (str == "") { alert("Enter a number in the field, please.") return false } for (var i = 0; i < str.length; i++) { var ch = str.substring(i, i + 1) if (ch < "0" || ch > "9") { alert("Try a number, please.") return false } } var num = 0 + str if (num < min || num > max) { alert("Try a number from 1 to 10.") return false } return true}function thanks() { alert("Thanks for your input.")}</script>
© Minder Chen, 1998-2002 JavaScript Example - 28
validate_form_2.htm (continued)<title>Form Data Validation</title></head><body><form>Please enter a small number: <input NAME="num"ONCHANGE="if (!checkNum(document.forms[0].num.value, 1, 10)) {this.focus();this.select(); return false;} else {thanks()}" VALUE="0"> <br><input type="submit">
</form><script LANGUAGE="JavaScript">document.write("<PRE>")document.writeln("Field name: " + document.forms[0].num.name)document.writeln("Field value: " + document.forms[0].num.value)document.write("</PRE>")</script>
</body></html>
© Minder Chen, 1998-2002 JavaScript Example - 29
<!-- This example is from JavaScript: The Definitive Guide, 3rd Edition. --><!-- That book and this example were Written by David Flanagan. --><!-- They are Copyright (c) 1996, 1997, 1998 O'Reilly & Associates. --><!-- This example is provided WITHOUT WARRANTY either expressed or implied.--><!-- You may study, use, modify, and distribute it for any purpose, --><!-- as long as this notice is retained. --><html><head><title>G:\js_example\js3examples\1-3.html</title></head><body><form NAME="loandata"> <table> <tr> <td COLSPAN="3"><big><b>Enter Loan Information:</b></big></td> </tr> <tr> <td>1)</td> <td>Amount of the loan (any currency):</td> <td><input TYPE="text" NAME="principal" SIZE="12" onChange="calculate()"></td> </tr> <tr> <td>2)</td> <td>Annual percentage rate of interest:</td> <td><input TYPE="text" NAME="interest" SIZE="12" onChange="calculate()"></td> </tr> <tr> <td>3)</td> <td>Repayment period in years:</td> <td><input TYPE="text" NAME="years" SIZE="12" onChange="calculate()"></td> </tr>
loan.htm
© Minder Chen, 1998-2002 JavaScript Example - 30
loan.htm (continued)<tr> <td COLSPAN="3"><big><b><input TYPE="button" VALUE="Compute"
onClick="calculate()"> Payment Information: </b></big></td> </tr> <tr> <td>4)</td> <td>Your monthly payment will be:</td> <td><input TYPE="text"
NAME="payment" SIZE="12"></td> </tr> <tr> <td>5)</td> <td>Your total payment will be:</td> <td><input TYPE="text" NAME="total" SIZE="12"></td> </tr> <tr> <td>6)</td> <td>Your total interest payments will be:</td> <td><input TYPE="text" NAME="totalinterest" SIZE="12"></td> </tr> </table></form>
© Minder Chen, 1998-2002 JavaScript Example - 31
loan.htm (continued)<script LANGUAGE="JavaScript">function calculate() { var principal = document.loandata.principal.value; var interest = document.loandata.interest.value / 100 / 12; var payments = document.loandata.years.value * 12; var x = Math.pow(1 + interest, payments); var monthly = (principal*x*interest)/(x-1); if (!isNaN(monthly) && (monthly != Number.POSITIVE_INFINITY) && (monthly != Number.NEGATIVE_INFINITY)) {
document.loandata.payment.value = round(monthly); document.loandata.total.value = round(monthly * payments) document.loandata.totalinterest.value = round((monthly * payments) - principal); } else { document.loandata.payment.value = ""; document.loandata.total.value = ""; document.loandata.totalinterest.value = ""; }}function round(x) { return Math.round(x*100)/100;}</script></body></html>
© Minder Chen, 1998-2002 JavaScript Example - 32
form_eval.htm<html><head>
<script LANGUAGE="JavaScript">
function compute(form) {
if (confirm("Are you sure?"))
form.result.value = eval(form.expr.value)
else
alert("Please come back again.")
}
</script>
<title></title></head><body>
<form>
Enter an expression: <input TYPE="text" NAME="expr" SIZE="15">
<input TYPE="button" VALUE="Calculate" ONCLICK="compute(this.form)">
<br>Result: <input TYPE="text" NAME="result" SIZE="15"> <br>
</form></body></html>
© Minder Chen, 1998-2002 JavaScript Example - 33
history.htm: history and location object<HTML><HEAD><TITLE>Navigation Using history Object</TITLE></HEAD><BODY><form><input type="button" value=" Back " onclick="history.back()"><input type="button" value="Forward" onclick="history.forward()"><br><br><input type="button" value="Reload" onclick="location.reload()"><input type="button" value="Load A New Page"
onclick="window.location.href='default.htm'"></form></body></html>
© Minder Chen, 1998-2002 JavaScript Example - 34
Frame Prevention Program<script LANGUAGE="JavaScript">
if (top.location != self.location)
{
top.location = self.location;
}
</script>
© Minder Chen and Lihui Zhang, 1999 - 2000 JavaScript - 201
frames[0]
frames[1]
frames[1],frame[0]
frames[1],frame[1]
top
parent
Self
window
parent.frame[0]
top.frame[1]
top.frame[0]
parent.parent
frames[1],frame[2]
© Minder Chen, 1998-2002 JavaScript Example - 35
setTimeOut.htm: setTimeout() function<HTML><HEAD><TITLE>Status Bar Clock</TITLE><SCRIPT LANGUAGE="JavaScript"><!--var flasher = false// calculate current time, determine flasher state,// and insert time into status bar every secondfunction updateTime() {
var now = new Date()var theHour = now.getHours()var theMin = now.getMinutes()var theTime = "" + ((theHour > 12) ? theHour - 12 : theHour)theTime += ((theMin < 10) ? ":0" : ":") + theMintheTime += (theHour >= 12) ? " pm" : " am"theTime += ((flasher) ? " " : "*")flasher = !flasherwindow.status = theTime// recursively call this function every second to keep timer going
timerID = setTimeout("updateTime()",1000)}//--></SCRIPT></HEAD>
<BODY onLoad="updateTime()"><h1>Look at the Status Bar</h1></BODY></HTML>
© Minder Chen, 1998-2002 JavaScript Example - 36
setInterval Function• setInterval(setInterval(expressionexpression, , msecmsec [, [, languagelanguage])])
– Repeatedly evaluates an expression after a specified number of milliseconds has elapsed.
– Returns an integer identifier representing the interval. Use this identifier to clear (stop) the interval.
– expression • String containing the script code to execute each time the interval
elapses.
– msec • Integer value or numeric string specifying the length of the interval, in
milliseconds.
– language • Optional. String specifying the language in which the code is
executed. – setInterval("rubberband()", 100);
• Sets a 0.1-second interval. Each time the interval elapses, letter space change.
© Minder Chen, 1998-2002 JavaScript Example - 37
set_TimeOut_Clock.htm: setInterval() function<HTML><HEAD><TITLE>My Clock</TITLE><SCRIPT LANGUAGE="JavaScript"><!--var flasher = falsefunction updateTime() {
var now = new Date()var theHour = now.getHours()var theMin = now.getMinutes()var theTime = "" + ((theHour > 12) ? theHour - 12 : theHour)theTime += ((theMin < 10) ? ":0" : ":") + theMintheTime += (theHour >= 12) ? " pm" : " am"theTime += ((flasher) ? " " : "*")flasher = !flasherdocument.all.time_display.value = theTime
}//--></SCRIPT></HEAD><BODY><input name="time_display" type="text"><script>
timerID = setInterval("updateTime()",1000)</script></BODY></HTML>
© Minder Chen, 1998-2002 JavaScript Example - 38
browser.htm: navigator object<HTML>
<BODY>
<H1>Browser Detection</H1>
<HR>
<SCRIPT LANGUAGE="JavaScript">
document.write("Browser version: " + navigator.appVersion + "<br>")
document.write("Browser name: <B>" + navigator.appName + "</B>.")
</SCRIPT>
</BODY>
</HTML>
© Minder Chen, 1998-2002 JavaScript Example - 39
mouse.htm<HTML><HEAD><STYLE> .on { font-size: 24;
text-decoration: underline;color: blue; }
.off{ font-size: 16; text-decoration: underline;color: blue; }
</STYLE><BODY STYLE = "font-family: Arial"><H1>AITC Web Site</H1><UL><LI> <A HREF = "profile.html" CLASS = "off" onMouseOver = "this.className ='on';" onMouseOut = "this.className = 'off';">Company Profile</A><LI> <A HREF = "expertise.html" CLASS = "off" onMouseOver = "this.className ='on';" onMouseOut = "this.className = 'off';">Expertise</A><LI> <A HREF = "course.html" CLASS = "off" onMouseOver = "this.className ='on';" onMouseOut = "this.className = 'off';">Training Courses</A></UL></BODY></HTML>
© Minder Chen, 1998-2002 JavaScript Example - 40
Table.htm<HTML><head><STYLE> .on { font-size: 24;
background-color: yellow;color: blue; }
.off { font-size: 24; background-color: ""; }
</STYLE></head> <BODY STYLE = "font-family: Arial"><table border=3> <tr><td class="off" onMouseOver = "this.className ='on';" onMouseOut = "this.className = 'off';">Home</td><td class="off" onMouseOver = "this.className ='on';"onMouseOut = "this.className = 'off';">Products</td></tr></table></BODY></HTML>
© Minder Chen, 1998-2002 JavaScript Example - 41
Lion.htm (Manipulating img tag)<html><head></head>
<body>
<img name="lion"
src="http://www.erols.com/aitc/slion.gif">
<br>
<input type="button" value="Show me the big lion"onClick="document.all.lion.src='http://www.erols.com/aitc/blion.gif';">
</body>
</html>
© Minder Chen, 1998-2002 JavaScript Example - 42
mouseover.htm<html><head><base TARGET="_top">
<script language="JavaScript">
<!-- hide JavaScript
function ChangeImage (ImageName,FileName) {
document[ImageName].src = FileName;
}
// done hiding ---------->
</script>
<title>Mouse Over</title>
<style>
<!--
a:link { color: blue; text-decoration: underline; font-weight: bold }
a:visited { color: purple; text-decoration: underline }
a:active {color: rgb(0,220,0); font-weight: bold}
a:hover { color: rgb(0,240,0); font-weight: bold }-->
</style></head><body>
<big>Choose your mode of transportation</big>
<table><tr><td width="100">
<a href="test1.htm" onMouseover="ChangeImage ('screen','car.gif'); return true" onMouseout="ChangeImage ('screen','default.gif'); return true">Car</a><br>
<a href="test2.htm" onMouseover="ChangeImage ('screen','bus.gif'); return true" onMouseout="ChangeImage ('screen','default.gif'); return true">Bus</a><br> </td>
<td> <img name="screen" src="default.gif" WIDTH="193" HEIGHT="103"></td>
</tr></table></body></html>
You can create animated image file only in gif format. This program allow you to create animated jpeg images
© Minder Chen, 1998-2002 JavaScript Example - 43
animated.htm<html><head><title></title><script language="JavaScript"><!-- // Website: http://www.sbrady.com/hotsource/if (document.images) { // Preloaded imagesdemo1 = new Image();demo1.src = "demo1.jpg";demo2 = new Image();demo2.src = "demo2.jpg";demo3 = new Image();demo3.src = "demo3.jpg"; }function timeimgs(numb) { // Reusable timer
thetimer = setTimeout("imgturn('" +numb+ "')", 1000); }function imgturn(numb) { // Reusable image turnerif (document.images) {
if (numb == "3") { // This will loop the imagedocument["demo"].src = eval("demo3.src");timeimgs('1');
}else {
document["demo"].src = eval("demo" + numb + ".src");timeimgs(numb = ++numb); }
} } // --></script> </head><body onload="timeimgs('2');"><div align="center"><img src="demo1.jpg" name="demo" width="100" height="100" alt="demo"></div></body></html>
© Minder Chen, 1998-2002 JavaScript Example - 44
Dynamic Positioning Example: move.htm<script> var i = 10function move(){
if (i < 200) {
i = i + 10;
document.all.x.style.top = (i + "px"); } else {
clearInterval(timerID) }
} </script><HTML> <BODY>This example demonstrates <B>Dynamic Positioning.</B>
<div id="x" overflow=scroll STYLE="position:relative; top:20px; left:10px"><img src="slion.gif">
</div> in a paragraph.
<script>
timerID = setInterval("move()", 100); </script></BODY></HTML>
© Minder Chen, 1998-2002 JavaScript Example - 45
Moving2.htm<script>max = window.screen.availHeightvar i = 10
var j = 10function move(){
if (i < max) {
i = i + 10; document.all.x.style.top = (i + "px");
} else {
i = 10 j = j +30 document.all.x.style.left = (j + "px")
}} </script><HTML> <BODY>This example demonstrates <B>Dynamic Positioning.</B><div id="x" overflow=scroll STYLE="position:absolute; top:20px; left:10px">
<img src="slion.gif" width="150" height="79"> </div> in a paragraph.
<script> timerID = setInterval("move()", 100); </script></BODY></HTML>
© Minder Chen, 1998-2002 JavaScript Example - 46
DContent.htm
<html><head></head><body>
<H1 id=myH1>Dynamic Content is <I>Very Cool</I>!</H1>
<script>
alert(document.all.myH1.innerHTML)
</script>
<input type="button" value="Show Me" onclick="document.all.myH1.innerHTML = 'You are <i>right</i>!' "><p> What is the sum of 6+5?
<input type="button" value="Tell me the answer" onclick="document.all.x.innerHTML = 'The sum of 6+5 = 11' "><div id=x></div>
</body></html>
© Minder Chen, 1998-2002 JavaScript Example - 47
innerhtml.htm (continued)<html><script LANGUAGE="JavaScript"><!--function display(myHTML){
document.all.result.innerHTML=myHTML;document.all.source.innerHTML = "<XMP>" + myHTML + "</XMP>";
}// --></script><head><title>Using innerHTML</title></head><body><form NAME="myForm"> <textarea ROWS="2" COLS="20" NAME="HTMLSource"></textarea><br> <input LANGUAGE="JavaScript" TYPE="button" value="Test It!" ONCLICK="display(document.forms['myForm'].HTMLSource.value);"> </form>Result: <div ID="result"></div>Source:<div ID="source"></div></body></html>
© Minder Chen, 1998-2002 JavaScript Example - 48
dhtml1.htm: using InnerText
<HTML><HEAD><TITLE>Dynamic HTML: innerText</TITLE></HEAD><BODY>
Enter your name: <INPUT name=guestName><br><INPUT style="background-color:yellow" TYPE="button" value="Continue" onclick="fillWords()"><SCRIPT> function fillWords(){ if (guestName.value != ""){ document.all.section2.style.display = 'block';
document.all.title1.innerText = "Hello " + guestName.value;}else alert("You must enter a guest name.");
}</SCRIPT><DIV ID=section2 style="display:none"><SPAN ID=title1 STYLE="color:blue" ></SPAN></DIV></BODY></HTML>
© Minder Chen, 1998-2002 JavaScript Example - 49
special.htm: innerHTML
<html><head>
<title>Special Effect 1</title>
</head>
<body>
<div id="sp">Spcial Effect</div><INPUT type="button" value="Test" name="button1" onClick="document.all.item('sp').innerHTML='<big>Special Effect!!!</big>';" >
</body>
</html>
© Minder Chen, 1998-2002 JavaScript Example - 50
Special2.htm<html><head><title>Special Effect 2</title><SCRIPT LANGUAGE=JavaScript><!--function effect() { if (i <= 7) {
document.all.item('sp').innerHTML="<font size=" + i + ">Special Effect</font>";
setTimeout("effect()", 1000); // 1000 ms = 1 secondi = i + 1;
}}--></SCRIPT></head><body><div id="sp">Special Effect</div><INPUT type="button" value="Test" name="button1" onClick="i = 1; effect();" ></body></html>
© Minder Chen, 1998-2002 JavaScript Example - 51
dom.htm<html><head><title>Document Object Model</title><style><!--#hide {display: off }#show {display: on }--></style></head><body bgcolor="white"><script> var i = 1; function getI(){ if (i < 2) {
i = i + 1; } else {
i = 1; }return i; } </script>
© Minder Chen, 1998-2002 JavaScript Example - 52
dom.htm (continued)<h1>Dom.htm <img name="myImg" border="0" src="test1.gif" width="239"
height="74"></h1>
<a href="#" onClick="document.myImg.src='test2.gif'">Change Image to Test2.gif</a><br>
<a href="#" onClick="var filename = 'test' + getI() + '.gif'; document.myImg.src=filename"; return true;>Rotate Image</a><br>
<form name="myForm1">
<p><select size="1" name="bgc" onChange="var list=document.myForm1.bgc; document.body.bgColor= list.options[list.selectedIndex].text; return true;">
<option>Red</option><option>Green</option><option>Blue</option>
<option>White</option><option>Brown</option></select>
<button type="button" name="MyButton" onClick="var list=document.myForm1.bgc; document.body.bgColor= list.options[list.selectedIndex].text; return true;">Change background Color </button>
</form>
<form name="myForm2">
<input type="text" name="Text1" size="20" value="Default value">
<button name="myButton2" onClick="document.myForm2.Text1.value = 'Hello World';"> Say Hello</button>
</form>
© Minder Chen, 1998-2002 JavaScript Example - 53
dom.htm (continued)<div id="divHello" style="width: 182; display: none; height: 52">
<font face="Albertus Extra Bold" size="6">Say Hello</font>
</div>
<p><input type="button" value="Display" name="B1"
onClick="document.all.divHello.style.display=''">
<input type="button" value="No Display" name="B2"
onClick="document.all.divHello.style.display='none'">
<input type="button" value="Visibile" name="B3"
onClick="document.all.divHello.style.visibility='visible'">
<input type="button" value="Not Visible" name="B4"
onClick="document.all.divHello.style.visibility='hidden'"> </p>
</body></html>
© Minder Chen, 1998-2002 JavaScript Example - 54
selectGo.htm <html><head><title>Select and Popup</title><script language="JavaScript"><!--function openPop(form) {var url=(form.dir.options[form.dir.selectedIndex].value);myWindow = window.open(url, 'myWindow', 'toolbar=no, location=no,
directories=no, status=no, menubar=no, scrollbars=no, resizable=no,width=500,height=400');
}// --></script></head><body><form name="myform"><div align="center"><p><select name="dir" size="1"><option value="">Choose a Site</option><option value="http://www.yahoo.com/">Yahoo!</option><option value="http://www.excite.com/">Excite</option></select><input type="button" name="button" value="Go!"
onclick="openPop(this.form);"></p></div></form></body></html>
© Minder Chen, 1998-2002 JavaScript Example - 55
Associate.htm: Associate Array<html><head><title>Associate Array</title></head><body><script language = "JavaScript">var phone_book = new Array();phone_book["happy"] = "(203) 555-1234";phone_book["sleepy"] = "(203) 555-2345";phone_book["snoopy"] = "(203) 555-4321";function displayNumber(phone_book, entry){ var the_number = phone_book[entry];
window.document.the_form.number_box.value = the_number; }</script><b>The Phone Book Using Associate Array</b><form name="the_form"><b>Name:</b><select onChange = "displayNumber(phone_book, this.options[selectedIndex].value);"><option value="happy">Happy<option value="sleepy">Sleepy<option value="snoopy">Snoopy</select><br><b>Number:</b><input type="text" name="number_box" value=""></form></body></html>
© Minder Chen, 1998-2002 JavaScript Example - 56
Opening Another Window
<!-- TWO STEPS TO INSTALL WINDOW POSITION:
1. Paste the first code in the HEAD of your HTML document 2. Add the last coding to the BODY of your HTML document -->
<!-- STEP ONE: Paste the first code in the HEAD of your HTML document -->
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- This script and many more are available free online at --><!-- The JavaScript Source!! http://javascript.internet.com -->
<!-- Beginfunction win() {msg=window.open("","msg","height=200,width=200,left=80,top=80");msg.document.write("<html><title>Windows!</title>");msg.document.write("<body bgcolor='white' onblur=window.close()>");msg.document.write("<center>page content here</center>");msg.document.write("</body></html><p>");
© Minder Chen, 1998-2002 JavaScript Example - 57
// If you just want to open an existing HTML page in the // new window, you can replace win()'s coding above with:// window.open("page.html","","height=200,width=200,left=80,top=80");}// End --></script><!-- STEP TWO: Add the last coding to the BODY of your HTML document --><BODY><body bgcolor="white"><center><form><input type="button" value="Open Window" onclick="win()"></form></center><!-- Or you may use: <a href="javascript:win()">Open Window</a> --><p><center><font face="arial, helvetica" size="-2">Free JavaScripts provided<br>by <a href="http://javascriptsource.com">The JavaScript Source</a></font></center><p>
© Minder Chen, 1998-2002 JavaScript Example - 58
Open Another Page via JavaScript
<INPUT type="Submit" value="View Result"
onclick = "window.open('RatingResult.aspx', null, 'height=400,width=600,top=20,left=20,channelmode=0, directories=0,fullscreen=0,location=0,menubar=0, resizable=1,scrollbars=1,status=1,titlebar=0,toolbar=0')">