Presentation is loading. Please wait.

Presentation is loading. Please wait.

© Minder Chen, 1998-2002 JavaScript Example - 1 Learning JavaScript By Examples by Minder Chen

Similar presentations


Presentation on theme: "© Minder Chen, 1998-2002 JavaScript Example - 1 Learning JavaScript By Examples by Minder Chen"— Presentation transcript:

1 © Minder Chen, 1998-2002 JavaScript Example - 1 Learning JavaScript By Examples by Minder Chen mchen@gmu.edu http://65.168.115.5/dhtml/javascript/

2 © 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

3 © 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="…." 3 X: X=Y S1S2 True False TempConvert(32, X) TempConvert(F, C) F C

4 © Minder Chen, 1998-2002 JavaScript Example - 4 hello_world.htm Hello World! <!-- document.write(" Write to the browser ") document.write("Hello World") // --> 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.

5 © Minder Chen, 1998-2002 JavaScript Example - 5 alert.htm Alert() alert('You clicked the button') <input type="button" value="Alert" onClick="alert('You clicked the button')"> 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.

6 © Minder Chen, 1998-2002 JavaScript Example - 6 function_square.htm: function call <!-- to hide script contents from old browsers function square(i) { // document.write("The call passed ", i," to the function."," ") return i * i } // end hiding contents from old browsers --> document.write("The function square() returned ",square(5),".") All done. The call passed 5 to the function. The function square() returned 25. All done.

7 © 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"

8 © Minder Chen, 1998-2002 JavaScript Example - 8

9 © Minder Chen, 1998-2002 JavaScript Example - 9 File.htm: Include JavaScript Source Code file.htm Include File file.js document.write("Hello world!") document.write("from an include file.js file")

10 © Minder Chen, 1998-2002 JavaScript Example - 10 prompt.htm Prompt() function on_prompt() { var ans ans = prompt("What is your name?", "Enter Your Name Here"); document.write("Hello " + ans + "!") } on_prompt(); Hello Minder Chen! on_prompt( ) is a user-defined function.

11 © Minder Chen, 1998-2002 JavaScript Example - 11 status.htm: onMouseOver and onMouseOut Events Event Use onMouseOver event of a hypertext link element to display text at Browser window's status bar. <a href="http://www.erols.com/aitc" onMouseOver="window.status='Visit AITC web site'; return true" onMouseOut="window.status='Done'; return true"> AITC 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

12 © Minder Chen, 1998-2002 JavaScript Example - 12 Reference HTML ElementsHello_button.htm Message: <input type="button" value="Say Hello" onClick= " window.document.form1.text1.value ='Hello World' "> window document form textbutton

13 © Minder Chen, 1998-2002 JavaScript Example - 13 Building Interactive Applications <!-- Beginning of JavaScript - function MsgBox (textstring) { alert (textstring) } // - End of JavaScript - -->

14 © Minder Chen, 1998-2002 JavaScript Example - 14 scope_variable.htm: Scope of Variables Scope of Variables var gv1 = "10 global"; gv2 = "20 global"; function test() { var lv1="5 local"; var gv1 = "10 local redefined"; document.write("into the function "); document.write("gv1=", gv1, " "); document.write("gv2=", gv2, " "); document.write("lv1=", lv1, " "); document.write("out of the function "); } document.write("into the global "); document.write("gv1=", gv1, " "); document.write("gv2=", gv2, " "); test(); document.write("out of the global "); into the global gv1=10 global gv2=20 global into the function gv1=10 local redefined gv2=20 global lv1=5 local out of the function out of the global

15 © Minder Chen, 1998-2002 JavaScript Example - 15 Document Object Model –document.forms[0], document.forms[1],.. –document.formName –document.formName.elements[index] –document.formName.formElementName –document.formName.formElementName.property

16 © Minder Chen, 1998-2002 JavaScript Example - 16 add2.htm Add Two Number function calculate(myForm) { var i; i = parseInt(myForm.T1.value) + parseInt(myForm.T2.value); myForm.T3.value = i; }</script> a = b = a + b = <input LANGUAGE="JavaScript" TYPE="button" VALUE="Calculate" ONCLICK="calculate(this.form)"> thisthis refers to whatever object contains the script in which the keywords is used. thisIn this script, 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. thisIn this script, this refers to the calculate button. this.formthis.form refers to the form that contains the form element object.

17 © Minder Chen, 1998-2002 JavaScript Example - 17 cal.htm Calculations <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? Kilogram (Kg)? Move mouse over me!

18 © Minder Chen, 1998-2002 JavaScript Example - 18 calculator2.htm Calculate Two Numbers <!-- function calculate(myForm) { var a, b, result, error_msg; var op = myForm.D1.value a = 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" }

19 © Minder Chen, 1998-2002 JavaScript Example - 19 calculator2.htm (continued) if (error_msg=="") { switch (op) { case "+": result = a + b break case "-": result = a - b break case "*": result = a * b break case "/": result = a / b break } myForm.T3.value = result } else { alert(error_msg) } // -->

20 © Minder Chen, 1998-2002 JavaScript Example - 20 calculator2.htm (continued) a = + - * / b = result = <input LANGUAGE="JavaScript" TYPE="button" VALUE="Calculate" ONCLICK="calculate(document.form1);" NAME="B1">

21 © Minder Chen, 1998-2002 JavaScript Example - 21 telltime.htm <!-- // 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(" Welcome to the world of JScript. ") document.write(" Just in case you were wondering, It's " + d + ".") //--> Good evening! Welcome to the world of JScript. Just in case you were wondering, It's Thu Jul 15 21:21:49 EDT 1999.

22 © Minder Chen, 1998-2002 JavaScript Example - 22 JavaScript: Looping For Loop Looping example: var i, total total = 0 for (i = 1; i<=10; i++) { document.write("i = " + i + " ") total = total + i } document.write("total = " + total + " ") Looping example: i = 1 i = 2 i = 3 i = 4 i = 5 i = 6 i = 7 i = 8 i = 9 i = 10 total = 55

23 © Minder Chen, 1998-2002 JavaScript Example - 23 write.htm Document.write document.write(" Client-side JavaScript "); for(i = 1; i<=10; i++) { document.write(i + " 2 = " + i*i + " "); }

24 © Minder Chen, 1998-2002 JavaScript Example - 24 Looping and Array For Loop and Array Looping and Array var i, total var x = new Array(66, 77, 88, 99, 55) total = 0 document.write(" 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 "); for (i=0; i< x.length; i++) { document.write(" i= " + i + " " + "x[" + i + "]=" + x[i] + " "); total = total + x[i]; } document.write("Total = " + total + " ");

25 © Minder Chen, 1998-2002 JavaScript Example - 25 Multiplication Table: loop2.htm For Loop Multiplication table: var i, j document.write(" ") for (i = 1; i<=12; i++) { document.write(" ") for (j = 1; j<=12; j++) { document.write(" " + i + "*" + j + "= " + i*j + " ") } document.write(" ") } document.write(" ")

26 © 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.

27 © Minder Chen, 1998-2002 JavaScript Example - 27 validate_form_2.htm: Form Input Data Validation 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 "9") { alert("Try a number, please.") return false } var num = 0 + str if (num max) { alert("Try a number from 1 to 10.") return false } return true } function thanks() { alert("Thanks for your input.") }

28 © Minder Chen, 1998-2002 JavaScript Example - 28 validate_form_2.htm (continued) Form Data Validation 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"> document.write(" ") document.writeln("Field name: " + document.forms[0].num.name) document.writeln("Field value: " + document.forms[0].num.value) document.write(" ")

29 © Minder Chen, 1998-2002 JavaScript Example - 29 G:\js_example\js3examples\1-3.html Enter Loan Information: 1) Amount of the loan (any currency): 2) Annual percentage rate of interest: 3) Repayment period in years: loan.htm

30 © Minder Chen, 1998-2002 JavaScript Example - 30 loan.htm (continued) Payment Information: 4) Your monthly payment will be: <input TYPE="text" NAME="payment" SIZE="12"> 5) Your total payment will be: 6) Your total interest payments will be:

31 © Minder Chen, 1998-2002 JavaScript Example - 31 loan.htm (continued) 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; }

32 © Minder Chen, 1998-2002 JavaScript Example - 32 form_eval.htm function compute(form) { if (confirm("Are you sure?")) form.result.value = eval(form.expr.value) else alert("Please come back again.") } Enter an expression: Result:

33 © Minder Chen, 1998-2002 JavaScript Example - 33 history.htm: history and location object Navigation Using history Object

34 © Minder Chen, 1998-2002 JavaScript Example - 34 Frame Prevention Program if (top.location != self.location) { top.location = self.location; }

35 © Minder Chen, 1998-2002 JavaScript Example - 35 setTimeOut.htm: setTimeout() function Status Bar Clock <!-- var flasher = false // calculate current time, determine flasher state, // and insert time into status bar every second function updateTime() { var now = new Date() var theHour = now.getHours() var theMin = now.getMinutes() var theTime = "" + ((theHour > 12) ? theHour - 12 : theHour) theTime += ((theMin < 10) ? ":0" : ":") + theMin theTime += (theHour >= 12) ? " pm" : " am" theTime += ((flasher) ? " " : "*") flasher = !flasher window.status = theTime // recursively call this function every second to keep timer going timerID = setTimeout("updateTime()",1000) } //--> Look at the Status Bar

36 © Minder Chen, 1998-2002 JavaScript Example - 36 setInterval Function setInterval(expression, msec [, language])setInterval(expression, msec [, language]) –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.

37 © Minder Chen, 1998-2002 JavaScript Example - 37 set_TimeOut_Clock.htm: setInterval() function My Clock <!-- var flasher = false function updateTime() { var now = new Date() var theHour = now.getHours() var theMin = now.getMinutes() var theTime = "" + ((theHour > 12) ? theHour - 12 : theHour) theTime += ((theMin < 10) ? ":0" : ":") + theMin theTime += (theHour >= 12) ? " pm" : " am" theTime += ((flasher) ? " " : "*") flasher = !flasher document.all.time_display.value = theTime } //--> timerID = setInterval("updateTime()",1000)

38 © Minder Chen, 1998-2002 JavaScript Example - 38 browser.htm: navigator object Browser Detection document.write("Browser version: " + navigator.appVersion + " ") document.write("Browser name: " + navigator.appName + ".")

39 © Minder Chen, 1998-2002 JavaScript Example - 39 mouse.htm.on{ font-size: 24; text-decoration: underline; color: blue; }.off{ font-size: 16; text-decoration: underline; color: blue; } AITC Web Site <A HREF = "profile.html" CLASS = "off" onMouseOver = "this.className ='on';" onMouseOut = "this.className = 'off';">Company Profile <A HREF = "expertise.html" CLASS = "off" onMouseOver = "this.className ='on';" onMouseOut = "this.className = 'off';">Expertise <A HREF = "course.html" CLASS = "off" onMouseOver = "this.className ='on';" onMouseOut = "this.className = 'off';">Training Courses

40 © Minder Chen, 1998-2002 JavaScript Example - 40 Table.htm.on{ font-size: 24; background-color: yellow; color: blue; }.off{ font-size: 24; background-color: ""; } <td class="off" onMouseOver = "this.className ='on';" onMouseOut = "this.className = 'off';">Home <td class="off" onMouseOver = "this.className ='on';" onMouseOut = "this.className = 'off';">Products

41 © Minder Chen, 1998-2002 JavaScript Example - 41 Lion.htm (Manipulating img tag) <img name="lion" src="http://www.erols.com/aitc/slion.gif"> <input type="button" value="Show me the big lion" onClick="document.all.lion.src='http://www.erols.com/aitc/blion.gif';">

42 © Minder Chen, 1998-2002 JavaScript Example - 42 mouseover.htm <!-- hide JavaScript function ChangeImage (ImageName,FileName) { document[ImageName].src = FileName; } // done hiding ----------> Mouse Over <!-- 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 }--> Choose your mode of transportation Car Bus You can create animated image file only in gif format. This program allow you to create animated jpeg images

43 © Minder Chen, 1998-2002 JavaScript Example - 43 animated.htm <!-- // Website: http://www.sbrady.com/hotsource/ if (document.images) { // Preloaded images demo1 = 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 turner if (document.images) { if (numb == "3") { // This will loop the image document["demo"].src = eval("demo3.src"); timeimgs('1'); } else { document["demo"].src = eval("demo" + numb + ".src"); timeimgs(numb = ++numb); } } } // -->

44 © Minder Chen, 1998-2002 JavaScript Example - 44 Dynamic Positioning Example: move.htm var i = 10 function move() { if (i < 200) { i = i + 10; document.all.x.style.top = (i + "px"); } else { clearInterval(timerID) } This example demonstrates Dynamic Positioning. in a paragraph. timerID = setInterval("move()", 100);

45 © Minder Chen, 1998-2002 JavaScript Example - 45 Moving2.htm max = window.screen.availHeight var i = 10 var j = 10 function 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") } This example demonstrates Dynamic Positioning. in a paragraph. timerID = setInterval("move()", 100);

46 © Minder Chen, 1998-2002 JavaScript Example - 46 DContent.htm Dynamic Content is Very Cool ! alert(document.all.myH1.innerHTML) <input type="button" value="Show Me" onclick="document.all.myH1.innerHTML = 'You are right !' "> 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' ">

47 © Minder Chen, 1998-2002 JavaScript Example - 47 innerhtml.htm (continued) <!-- function display(myHTML) { document.all.result.innerHTML=myHTML; document.all.source.innerHTML = " " + myHTML + " "; } // --> Using innerHTML <input LANGUAGE="JavaScript" TYPE="button" value="Test It!" ONCLICK="display(document.forms['myForm'].HTMLSource.value);"> Result: Source:

48 © Minder Chen, 1998-2002 JavaScript Example - 48 dhtml1.htm: using InnerText Dynamic HTML: innerText Enter your name: <INPUT style="background-color:yellow" TYPE="button" value="Continue" onclick="fillWords()"> 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."); }

49 © Minder Chen, 1998-2002 JavaScript Example - 49 special.htm: innerHTML Special Effect 1 Spcial Effect Special Effect!!! ';" >

50 © Minder Chen, 1998-2002 JavaScript Example - 50 Special2.htm Special Effect 2 <!-- function effect() { if (i <= 7) { document.all.item('sp').innerHTML=" Special Effect "; setTimeout("effect()", 1000); // 1000 ms = 1 second i = i + 1; } --> Special Effect

51 © Minder Chen, 1998-2002 JavaScript Example - 51 dom.htm Document Object Model <!-- #hide {display: off } #show {display: on } --> var i = 1; function getI() { if (i < 2) { i = i + 1; } else { i = 1; } return i; }

52 © Minder Chen, 1998-2002 JavaScript Example - 52 dom.htm (continued) Dom.htm Change Image to Test2.gif Rotate Image Red Green Blue White Brown Change background Color Say Hello

53 © Minder Chen, 1998-2002 JavaScript Example - 53 dom.htm (continued) Say Hello

54 © Minder Chen, 1998-2002 JavaScript Example - 54 selectGo.htm Select and Popup <!-- 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'); } // --> Choose a Site Yahoo! Excite

55 © Minder Chen, 1998-2002 JavaScript Example - 55 Associate.htm: Associate Array Associate Array 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; } The Phone Book Using Associate Array Name: Happy Sleepy Snoopy Number:

56 © 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 --> <!-- Begin function win() { msg=window.open("","msg","height=200,width=200,left=80,top=80"); msg.document.write(" Windows! "); msg.document.write(" "); msg.document.write(" page content here "); msg.document.write(" ");

57 © 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 --> Open Window --> Free JavaScripts provided by The JavaScript Source

58 © 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')" >


Download ppt "© Minder Chen, 1998-2002 JavaScript Example - 1 Learning JavaScript By Examples by Minder Chen"

Similar presentations


Ads by Google