Download presentation
Presentation is loading. Please wait.
Published byClarence Briggs Modified over 9 years ago
1
CSW131 Steven Battilana 1 CSW 131 – Supplement 2 Working with JavaScript (NOT in Textbook) Prepared by Prof. B. for use in CSW 131 (Intro. To Web Design) Index
2
CSW131 Steven Battilana 2 INDEX (use links to view topic – slide number is black) 3 Some Key Things (But Not All) You Can Do With JavaScript & Simple GuidelinesSome Key Things (But Not All) You Can Do With JavaScript & Simple Guidelines 4 Write JavaScript (Text) to Your Web DocumentWrite JavaScript (Text) to Your Web Document 5 Using External JavaScriptUsing External JavaScript 6 Executing JavaScript In BlocksExecuting JavaScript In Blocks 7 JavaScript CommentsJavaScript Comments 8 JavaScript VariablesJavaScript Variables 9 JavaScript Arithmetic OperatorsJavaScript Arithmetic Operators 10 JavaScript Assignment OperatorsJavaScript Assignment Operators 11 The + Operator Used on Strings and Combined with Numbers [1] 12 [2]The + Operator Used on Strings and Combined with Numbers [1][2] 13 Comparison and Logical Operators [1] 14 [2]Comparison and Logical Operators [1][2] 15 Conditional StatementsConditional Statements 16 Conditional Statements: IfConditional Statements: If 17 Conditional Statements: If…elseConditional Statements: If…else 18 Conditional Statements: If…else if…else 1 of 2 19 2 of 2Conditional Statements: If…else if…else 1 of 22 of 2 20 Conditional Statements: Switch 1 of 2 21 2 of 2Conditional Statements: Switch 1 of 22 of 2 22 Popup Boxes: AlertPopup Boxes: Alert 23 Popup Boxes: ConfirmPopup Boxes: Confirm 24 Popup Boxes: PromptPopup Boxes: Prompt 25 More about functionsMore about functions 26 Loops: forLoops: for 27 Loops: whileLoops: while 28 Loops: do…whileLoops: do…while 29 Loops: break StatementLoops: break Statement 30 Loops: continue StatementLoops: continue Statement 31 Loops: for…in StatementLoops: for…in Statement 40 40 Notes, Use, Other ResourcesNotes, Use, Other Resources Extras 32 33 34 32 Validate a Form 1 of 3 33 2 of 3 34 3 of 3Validate a Form 1 of 32 of 33 of 3 35 35 Open a New WindowOpen a New Window 36 37 36 Hide and Show Elements 1 of 2 37 2 of 2Hide and Show Elements 1 of 22 of 2 38 39 38 Swap Images 1 of 2 39 2 of 2Swap Images 1 of 2 2 of 2 Important Reminder Use /* */ “wrapper” as needed. (see slide 3)
3
CSW131 Steven Battilana 3 Some Key Things (But Not All) You Can Do With JavaScript & Simple JavaScript Guidelines [Back to INDEX] [Back to INDEX] [Back to INDEX] Code uses object-based model & can manipulate everything on page Not Secure, but downloads with web page and runs fast on user PC Some Key Things (But Not All) You Can Do (within as external page) Create small(er) programs within (X)HTML pages Create event user-driven reactions Read and write (X)HTML elements Validate data (like form fields) Detect the user’s browser and react accordingly Create cookies to store visitor’s (user’s) data Use one or more scripts in,, and or both Simple Guidelines JavaScript is case sensitive: careful with capitalization! White space is ignored: so make it easily readable. Tags:opens /* */ –Note special tags for validators (see xhtml_doc$JS.html) You can break up a code line if it is text by using \ »document.write("Hi there, how the heck \ are you doing?"); * Important!: Use /* */ “wrapper” as needed. * “Wrapper” forces CDATA rather than auto-XHTML #PCDATA (use as needed)
4
CSW131 Steven Battilana 4 Write JavaScript (Text) to Your Web Document [Back to INDEX] [Back to INDEX] [Back to INDEX] document.write precedes ("what you want to write to your web document"); document.write precedes ("what you want to write to your web document"); Download supp2.zip from our Hot! Page, Save & unzip in class_work folder, open xhtml_doc$.html. On new line before type: [required OPEN tag] document.write("Text for my web page document"); [required CLOSE tag] you can also add (X)HTML within the JavaScript document.write(" Text for my web page document "); Stop JavaScript from showing as page content when it is deactivated document.write(" Text for my web page document "); --> Download supp2.zip from our Hot! Page, Save & unzip in class_work folder, open xhtml_doc$.html. On new line before type: [required OPEN tag] document.write("Text for my web page document"); [required CLOSE tag] you can also add (X)HTML within the JavaScript document.write(" Text for my web page document "); Stop JavaScript from showing as page content when it is deactivated document.write(" Text for my web page document "); --> Save in supp2 as write_js_text.html. Try adding wrapper. Save and view. Save in supp2 as write_js_text.html. Try adding wrapper. Save and view. Open js_xhtml_doc$.html…a simple default file to start a JS XHTML page. Open js_xhtml_doc$.html…a simple default file to start a JS XHTML page.
5
CSW131 Steven Battilana 5 Using External JavaScript [Back to INDEX] [Back to INDEX] [Back to INDEX] You can use the same JavaScript on several pages by referring to an external page using this format: You can use the same JavaScript on several pages by referring to an external page using this format: (xyz can be any name)
6
CSW131 Steven Battilana 6 Executing JavaScript In Blocks [Back to INDEX] [Back to INDEX] [Back to INDEX] JavaScript can be grouped in blocks using curly braces JavaScript can be grouped in blocks using curly braces { { (beginning) } } (ending) so a sequence of statements will execute together This is used to a large extend for functions and conditions, which we will get into shortly. This is used to a large extend for functions and conditions, which we will get into shortly.
7
CSW131 Steven Battilana 7 JavaScript Comments [Back to INDEX] [Back to INDEX] [Back to INDEX] Single line comments: // Write a heading document.write(" This is a heading "); Single line comments: // Write a heading document.write(" This is a heading "); Multi-line comments: /* The code below should be executed for the upcoming holiday sale only! */ Multi-line comments: /* The code below should be executed for the upcoming holiday sale only! */ [assume valid script is written here]; Comments used at end of a line of code: document.write(" The heading "); // main heading Comments used at end of a line of code: document.write(" The heading "); // main heading
8
CSW131 Steven Battilana 8 JavaScript Variables [Back to INDEX] [Back to INDEX] [Back to INDEX] Variables can be declared WITH or WITHOUT values var x; [variable x WITHOUT a declared value] var x=7; [variable x WITH a declared value of 7] Variables can be declared WITH or WITHOUT values var x; [variable x WITHOUT a declared value] var x=7; [variable x WITH a declared value of 7]
9
CSW131 Steven Battilana 9 JavaScript Arithmetic Operators [Back to INDEX] [Back to INDEX] [Back to INDEX] JavaScript Arithmetic Operators JavaScript Arithmetic Operators Arithmetic operators are used to perform arithmetic between variables and/or values. Arithmetic operators are used to perform arithmetic between variables and/or values. Given that y=5, the table below explains the arithmetic operators: Given that y=5, the table below explains the arithmetic operators:
10
CSW131 Steven Battilana 10 JavaScript Assignment Operators [Back to INDEX] [Back to INDEX] [Back to INDEX] JavaScript Assignment Operators JavaScript Assignment Operators Assignment operators are used to assign values to JavaScript variables. Assignment operators are used to assign values to JavaScript variables. Given that x=10 and y=5, the table below explains the assignment operators : Given that x=10 and y=5, the table below explains the assignment operators : No remainder (Modulus)
11
CSW131 Steven Battilana 11 The + Operator Used on Strings and Combined with Numbers [Back to INDEX] [Back to INDEX] [Back to INDEX] Using the + operator on text strings concatenates the strings So if: txt1= "I’ll earn a"; Using the + operator on text strings concatenates the strings So if: txt1= "I’ll earn a"; txt2= "good grade"; txt3=txt1+txt2; becomes I’ll earn agood grade so add a space after a in txt1 or before good in txt2 or add a space within txt3 txt3=txt1+" "+txt2; which correctly becomes I’ll earn a good grade When the + operator is used combining strings + numbers the result is always a string (of characters): see the next page… When the + operator is used combining strings + numbers the result is always a string (of characters): see the next page…
12
CSW131 Steven Battilana 12 The + Operator Used on Strings and Combined with Numbers (CONT.) [Back to INDEX] [Back to INDEX][Back to INDEX] Try these combinations within an (X)HTML document (remembering the required start and end script tags) starting on a new line before : __________Below are the results__________ x=5+10; document.write(x); [result: addition with answer = 15] document.write(" "); [try without, then with these breaks] x="5"+"10"; document.write(x); [result: concatenation with answer = 510] document.write(" "); x=5+"10"; document.write(x); [result: concatenation with answer = 510] document.write(" "); x="5"+10; document.write(x); [result: concatenation with answer = 510] Try these combinations within an (X)HTML document (remembering the required start and end script tags) starting on a new line before : __________Below are the results__________ x=5+10; document.write(x); [result: addition with answer = 15] document.write(" "); [try without, then with these breaks] x="5"+"10"; document.write(x); [result: concatenation with answer = 510] document.write(" "); x=5+"10"; document.write(x); [result: concatenation with answer = 510] document.write(" "); x="5"+10; document.write(x); [result: concatenation with answer = 510] Save as operator_example.html and test. Save as operator_example.html and test.
13
CSW131 Steven Battilana 13 Comparison and Logical Operators [Back to INDEX] [Back to INDEX] [Back to INDEX] Comparison operators are used in logical statements to determine equality or difference between variables or values. Comparison operators are used in logical statements to determine equality or difference between variables or values. Given that x=5, the table below explains the comparison operators: Given that x=5, the table below explains the comparison operators: So a possible use would be: if (grade>=93) document.write("You earned an A!"); (and also an example of why you would use document.write) So a possible use would be: if (grade>=93) document.write("You earned an A!"); (and also an example of why you would use document.write)
14
CSW131 Steven Battilana 14 Comparison and Logical Operators (CONT.) [Back to INDEX] [Back to INDEX] [Back to INDEX] Logical operators are used to determine the logic between variables or values. Logical operators are used to determine the logic between variables or values. Given that x=6 and y=3, the table below explains the logical operators: Given that x=6 and y=3, the table below explains the logical operators: JavaScript also contains a conditional operator that assigns a value to a variable based on some condition, using this syntax: variablename=(condition)?value1[if TRUE]:value2[if FALSE] So as an example for greeting with the variable visitor: greeting=(visitor=="PRES")?"Dear President ":"Dear "; If the variable visitor has the value of "PRES“ (condition is TRUE), Then the variable greeting will be assigned the value "Dear President " Else it will be assigned "Dear" (condition is FALSE). JavaScript also contains a conditional operator that assigns a value to a variable based on some condition, using this syntax: variablename=(condition)?value1[if TRUE]:value2[if FALSE] So as an example for greeting with the variable visitor: greeting=(visitor=="PRES")?"Dear President ":"Dear "; If the variable visitor has the value of "PRES“ (condition is TRUE), Then the variable greeting will be assigned the value "Dear President " Else it will be assigned "Dear" (condition is FALSE).
15
CSW131 Steven Battilana 15 Conditional Statements [Back to INDEX] [Back to INDEX] [Back to INDEX] Conditional statements are used to perform different actions based on different conditions. Your code can do the following: Conditional statements are used to perform different actions based on different conditions. Your code can do the following: if statement - use this statement to execute code only if a specified condition is true if...else statement - use this statement to execute some code if the condition is true and other code if the condition is false if...else if....else statement - use this statement to select one of several blocks of code to be executed switch statement - use this statement to select one of many blocks of code to be executed The following pages demonstrate practical examples of each…
16
CSW131 Steven Battilana 16 Conditional Statements: If (CONT.) [Back to INDEX] [Back to INDEX] [Back to INDEX] An if statement uses this syntax: if (condition) { code to be executed if condition is true } So as an example for when this specific condition is true: //Write a "Good morning" greeting if //the time is less than 12 noon var d=new Date(); [commonly used var time=d.getHours(); variables] if (time Good morning! "); } An if statement uses this syntax: if (condition) { code to be executed if condition is true } So as an example for when this specific condition is true: //Write a "Good morning" greeting if //the time is less than 12 noon var d=new Date(); [commonly used var time=d.getHours(); variables] if (time Good morning! "); } Returning greeting as appropriate (and easy to change) Returning greeting as appropriate (and easy to change) Save as cond_statement_if.html Save as cond_statement_if.html
17
CSW131 Steven Battilana 17 Conditional Statements: If…else (CONT.) [Back to INDEX] [Back to INDEX] [Back to INDEX] An if…else statement uses this syntax: if (condition) { code to be executed if condition is true } else { code to be executed if condition is not true } So edit the if example in cond_statement_if.html : if (time < 12) { document.write("Good morning!"); } else { document.write("Good day!...I said good day!!!"); } Returning 1 of 2 greetings (again easy to change) An if…else statement uses this syntax: if (condition) { code to be executed if condition is true } else { code to be executed if condition is not true } So edit the if example in cond_statement_if.html : if (time < 12) { document.write("Good morning!"); } else { document.write("Good day!...I said good day!!!"); } Returning 1 of 2 greetings (again easy to change) Save as cond_statement_if…else.html Save as cond_statement_if…else.html
18
CSW131 Steven Battilana 18 Conditional Statements: If…else if…else 1 of 2 (CONT.) [Back to INDEX] [Back to INDEX] [Back to INDEX] An if…else if…else statement uses this syntax: if (condition1) { code to be executed if condition1 is true } else if (condition2) { code to be executed if condition2 is true } else { code to be executed if condition1 and condition2 are not true } An if…else if…else statement uses this syntax: if (condition1) { code to be executed if condition1 is true } else if (condition2) { code to be executed if condition2 is true } else { code to be executed if condition1 and condition2 are not true }
19
CSW131 Steven Battilana 19 Conditional Statements: If…else if…else 2 of 2 (CONT.) [Back to INDEX] [Back to INDEX] [Back to INDEX] So here is a good all day user greeting script using this code: var d = new Date(); var time = d.getHours(); if (time Good morning "); } else if (time 12 && Good afternoon "); } else { document.write(" Good evening "); } Returning 1 of several greetings (again easy to change) So here is a good all day user greeting script using this code: var d = new Date(); var time = d.getHours(); if (time Good morning "); } else if (time 12 && Good afternoon "); } else { document.write(" Good evening "); } Returning 1 of several greetings (again easy to change) Save as cond_statement_if…else_if…else.html Save as cond_statement_if…else_if…else.html
20
CSW131 Steven Battilana 20 Conditional Statements: Switch 1 of 2 (CONT.) [Back to INDEX] [Back to INDEX] [Back to INDEX] Use the switch statement to select one of many blocks of code to be executed. Following is the syntax: switch(n... i.e., var being switched) { case 1: execute code block 1 break; case 2: [allows use of as many cases as needed] execute code block 2 break; default: code to be executed if n is different from case 1 and 2 } Use the switch statement to select one of many blocks of code to be executed. Following is the syntax: switch(n... i.e., var being switched) { case 1: execute code block 1 break; case 2: [allows use of as many cases as needed] execute code block 2 break; default: code to be executed if n is different from case 1 and 2 } How it works: First the single expression n (most often a variable), is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. How it works: First the single expression n (most often a variable), is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Using break stops code from running the next case automatically.
21
CSW131 Steven Battilana 21 Conditional Statements: Switch 2 of 2 (CONT.) [Back to INDEX] [Back to INDEX] [Back to INDEX] Switch code example. Note all or some cases may be used (again easy to change). : //You will receive a different greeting based on what day //it is. Note that Sunday=0, Monday=1, Tuesday=2, etc. var d=new Date(); var theDay=d.getDay(); switch (theDay) { case 5: document.write("Finally Friday"); break; case 6: document.write("Super Saturday"); break; case 0: document.write("Sleepy Sunday"); break; default: document.write("I'm REALLY looking forward to this weekend!"); } Switch code example. Note all or some cases may be used (again easy to change). : //You will receive a different greeting based on what day //it is. Note that Sunday=0, Monday=1, Tuesday=2, etc. var d=new Date(); var theDay=d.getDay(); switch (theDay) { case 5: document.write("Finally Friday"); break; case 6: document.write("Super Saturday"); break; case 0: document.write("Sleepy Sunday"); break; default: document.write("I'm REALLY looking forward to this weekend!"); } Save as cond_statement_switch.html Save as cond_statement_switch.html
22
CSW131 Steven Battilana 22 Popup Boxes: Alert 1 of 3 [Back to INDEX] [Back to INDEX] [Back to INDEX] Open xhtml_doc$.html and on line before type ONLY the 3 BLACK lines: function showalert() [use a logical function name] { alert("Hello, world!"); } Open xhtml_doc$.html and on line before type ONLY the 3 BLACK lines: function showalert() [use a logical function name] { alert("Hello, world!"); } Save as jsalert_event.html, and view in browser. Save as jsalert_event.html, and view in browser. To give user control, use an event handler preceded by a function: To give user control, use an event handler preceded by a function: Type in green lines above (using showalert as function), then on the line after the tag type an opening form tag and create a button to enable the event Show the alert Save as jsalert_event.html, view in browser, and try button. Save as jsalert_event.html, view in browser, and try button.
23
CSW131 Steven Battilana 23 Popup Boxes: Confirm 2 of 3 [Back to INDEX] [Back to INDEX] [Back to INDEX] Unlike an Alert Box, a Confirm Box enables a user to accept a condition by clicking OK (true) or declining by clicking Cancel (or X for false). Unlike an Alert Box, a Confirm Box enables a user to accept a condition by clicking OK (true) or declining by clicking Cancel (or X for false). Edit the existing code in jsalert_event.html on line after function showalert showconfirm() [again, use a logical function name] { var r=confirm("Please click OK to accept or Cancel to decline"); if (r= =true) { document.write("Thank you for accepting our terms!"); } else document.write("Sorry, but you have declined our terms."); alert("Hello, world!"); } Edit the existing code in jsalert_event.html on line after function showalert showconfirm() [again, use a logical function name] { var r=confirm("Please click OK to accept or Cancel to decline"); if (r= =true) { document.write("Thank you for accepting our terms!"); } else document.write("Sorry, but you have declined our terms."); alert("Hello, world!"); } Then in the edit the button to enable the event [using the same function name as above] Show the alert our terms of use Then in the edit the button to enable the event [using the same function name as above] Show the alert our terms of use Save these changes as the file jsconfirm.html and test it in your browser. Save these changes as the file jsconfirm.html and test it in your browser.
24
CSW131 Steven Battilana 24 Popup Boxes: Prompt 3 of 3 [Back to INDEX] [Back to INDEX] [Back to INDEX] A Prompt Box lets you have user input a value before entering a page. When a prompt box pops up, the user will have to click either "OK", which returns their input value, or "Cancel" (returning no value) to proceed after entering an input value. A Prompt Box lets you have user input a value before entering a page. When a prompt box pops up, the user will have to click either "OK", which returns their input value, or "Cancel" (returning no value) to proceed after entering an input value. Edit the existing code in jsconfirm.html on line after function showconfirm showprompt () { var r=confirm("Please OK to accept or Cancel to decline"); var name=prompt("Please enter your name","(type your name here)"); if (r==true) if (name!=null && name!="") { document.write("Thank you for accepting our terms!"); document.write("Thank you " + name + ", for signing in! You're in for a treat."); } else document.write("Sorry, but you have declined our terms."); } Edit the existing code in jsconfirm.html on line after function showconfirm showprompt () { var r=confirm("Please OK to accept or Cancel to decline"); var name=prompt("Please enter your name","(type your name here)"); if (r==true) if (name!=null && name!="") { document.write("Thank you for accepting our terms!"); document.write("Thank you " + name + ", for signing in! You're in for a treat."); } else document.write("Sorry, but you have declined our terms."); } Then in the edit the button to enable the event Show the our terms of use sign in prompt Then in the edit the button to enable the event Show the our terms of use sign in prompt Save these changes as jsprompt.html and test it in your browser. Save these changes as jsprompt.html and test it in your browser.
25
CSW131 Steven Battilana 25 More about functions [Back to INDEX] [Back to INDEX] [Back to INDEX] Here are key use review points: Here are key use review points: Functions give you control as to when a script executes AND prevents execution while a web page loads They can be in the or of a web page, but to ensure your functions are loaded, in most cases place them in the Syntax:function functionname (var1, var2, …, varn) [ or just () ] { your code } [notice lower case letters are used] We have executed functions using event handlers (buttons, etc.) in the Return Statements are used to specify the value that is returned from the function, so functions that are going to return a value must use the return statement. In the example below the product of 2 numbers (a & b) is returned: In head: function product(a,b) { return a*b; } In body: document.write(product(17,7));
26
CSW131 Steven Battilana 26 Loops: for 1 of 6 [Back to INDEX] [Back to INDEX] [Back to INDEX] Writing code using a loop allows the same block of code to run over and over again with conditions you set instead of voluminous code. Writing code using a loop allows the same block of code to run over and over again with conditions you set instead of voluminous code. In JavaScript, there are two different kind of loops: In JavaScript, there are two different kind of loops: loops through a block of code for a set number of times for - loops through a block of code for a set number of times loops through a block of code while a set condition is true while - loops through a block of code while a set condition is true for syntax:for (var=startvalue;var<=endvalue;var=var+increment) { your code } for syntax:for (var=startvalue;var<=endvalue;var=var+increment) { your code } Example: (place code in of an XHTML file var i=0; for (i=0;i "); } Example: (place code in of an XHTML file var i=0; for (i=0;i "); } Save as jsforloop.html and test in browser. Save as jsforloop.html and test in browser. any comparing statement
27
CSW131 Steven Battilana 27 Loops: while 2 of 6 [Back to INDEX] [Back to INDEX] [Back to INDEX] As noted earlier, writing code using a while loop allows the same block of code to run over and over again while a set condition is true As noted earlier, writing code using a while loop allows the same block of code to run over and over again while a set condition is true while syntax: while (var<=endvalue) { your code } while syntax: while (var<=endvalue) { your code } Example: (place code in of an XHTML file var i=0; while (i "); i++; } Example: (place code in of an XHTML file var i=0; while (i "); i++; } Save as jswhileloop.html and test in browser. Save as jswhileloop.html and test in browser. any comparing statement
28
CSW131 Steven Battilana 28 Loops: do…while 3 of 6 [Back to INDEX] [Back to INDEX] [Back to INDEX] The do…while loop is a while loop variant. It executes the code once, then repeats the loop while a set condition is true The do…while loop is a while loop variant. It executes the code once, then repeats the loop while a set condition is true do…while syntax:do { [first runs once] your code } while (var<=endvalue) do…while syntax:do { [first runs once] your code } while (var<=endvalue) Example: (place code in of an XHTML file var i=0; do { document.write("The number is " + i); document.write(" "); i++; } while (i Example: (place code in of an XHTML file var i=0; do { document.write("The number is " + i); document.write(" "); i++; } while (i Save as jsdowhileloop.html and test in browser. Save as jsdowhileloop.html and test in browser. any comparing statement
29
CSW131 Steven Battilana 29 Loops: break Statement 4 of 6 [Back to INDEX] [Back to INDEX] [Back to INDEX] The break statement will break the loop and continue executing the code that follows after the loop (if any). The break statement will break the loop and continue executing the code that follows after the loop (if any). Example: (place code in of an XHTML file var i=0; for (i=0;i "); } Example: (place code in of an XHTML file var i=0; for (i=0;i "); } Save as jsbreakloop.html and test in browser. Save as jsbreakloop.html and test in browser. Note: loop stops at 3; since no code is after the loop, script ends. Note: loop stops at 3; since no code is after the loop, script ends. any comparing statement
30
CSW131 Steven Battilana 30 Loops: continue Statement 5 of 6 [Back to INDEX] [Back to INDEX] [Back to INDEX] The continue statement will break the current loop AND continue with the next value. The continue statement will break the current loop AND continue with the next value. Example: (place code in of an XHTML file var i=0 for (i=0;i "); } Example: (place code in of an XHTML file var i=0 for (i=0;i "); } Save as jscontinueloop.html and test in browser. Save as jscontinueloop.html and test in browser. Note: loop omits 3, but unlike break, continues then through end (10) Note: loop omits 3, but unlike break, continues then through end (10) any comparing statement
31
CSW131 Steven Battilana 31 Loops: for…in Statement 6 of 6 [Back to INDEX] [Back to INDEX] [Back to INDEX] The for...in statement loops through the elements of an array or through the properties of an object. The for...in statement loops through the elements of an array or through the properties of an object. for…in syntax:for (variable in object) { code to be executed } for…in syntax:for (variable in object) { code to be executed } Example: (place code in of an XHTML file var x; var stooges = new Array(); stooges[0] = "Moe"; stooges[1] = "Larry"; stooges[2] = "Curly"; for (x in stooges) { document.write(stooges[x] + " "); } Save as jsforinloop.html and test in browser. We MUST really add "Shemp ", save and test again! Example: (place code in of an XHTML file var x; var stooges = new Array(); stooges[0] = "Moe"; stooges[1] = "Larry"; stooges[2] = "Curly"; for (x in stooges) { document.write(stooges[x] + " "); } Save as jsforinloop.html and test in browser. We MUST really add "Shemp ", save and test again!
32
CSW131 Steven Battilana 32 Validate a Form [Back to INDEX] [Back to INDEX] [Back to INDEX] JavaScript treats document objects as a child and uses dot notation JavaScript treats document objects as a child and uses dot notation value is assessed at the end of the statement value is assessed at the end of the statement Conditional statements use if statements followed by the true code, and else can be used if false code is needed Conditional statements use if statements followed by the true code, and else can be used if false code is needed = = is used to test for equality, while =! tests for inequality = = is used to test for equality, while =! tests for inequality Open contact.html in tyvindustries folder, and on the line before type function validateform() [a logical variable name we have created] { [here we are setting conditions if users leave fields blank] if(document.contactform.firstname.value = = "") { [this happens if true] } if(document.contactform.lastname.value = = "") { [this happens if true] } if(document.contactform.email.value = = "") { [this happens if true] } } there’s more… Open contact.html in tyvindustries folder, and on the line before type function validateform() [a logical variable name we have created] { [here we are setting conditions if users leave fields blank] if(document.contactform.firstname.value = = "") { [this happens if true] } if(document.contactform.lastname.value = = "") { [this happens if true] } if(document.contactform.email.value = = "") { [this happens if true] } } there’s more… (nospace) (no space)
33
CSW131 Steven Battilana 33 Validate a Form (CONT.) [Back to INDEX] [Back to INDEX] [Back to INDEX] Set message boxes regarding errors and create a variable (var) to help count errors: function validateform() { var error = ""; [var name you create is error in this case] if(document.contactform.firstname.value = = "") { error = error + "Please enter your first name\n"; [\n=new line] } if(document.contactform.lastname.value = = "") { error = error + "Please enter your last name\n"; } if(document.contactform.email.value = = "") { Set message boxes regarding errors and create a variable (var) to help count errors: function validateform() { var error = ""; [var name you create is error in this case] if(document.contactform.firstname.value = = "") { error = error + "Please enter your first name\n"; [\n=new line] } if(document.contactform.lastname.value = = "") { error = error + "Please enter your last name\n"; } if(document.contactform.email.value = = "") { error = error + "Please enter your email\n"; } if(error == "") [if there are NO errors] { { return true; [form is submitted with no errors] } else { } else { alert(error); [alert message appears with appropriate error messages] return false; } } there’s more… } } there’s more…
34
CSW131 Steven Battilana 34 Validate a Form (CONT.) [Back to INDEX] [Back to INDEX] [Back to INDEX] Finally, edit the [user event ] Finally, edit the [user event ] Save contact.html and test submitting form with various text fields empty. Save contact.html and test submitting form with various text fields empty.
35
CSW131 Steven Battilana 35 Open a New Window [Back to INDEX] [Back to INDEX] [Back to INDEX] JavaScript can create the dreaded, misused pop-up window (ads), but used properly (i.e., Help, etc.) they are useful JavaScript can create the dreaded, misused pop-up window (ads), but used properly (i.e., Help, etc.) they are useful open starts a new window, which should be a user initiated event open starts a new window, which should be a user initiated event Use xhtml_doc$.html to create jsnewwindow.html, make title Opening a New Window, then on the line before type function openwin() [our logically named function] { open('tyvindustries/about.html', 'newwin'); [use any file] } then on the line after type Open Window Use xhtml_doc$.html to create jsnewwindow.html, make title Opening a New Window, then on the line before type function openwin() [our logically named function] { open('tyvindustries/about.html', 'newwin'); [use any file] } then on the line after type Open Window Save jsnewwindow.html and test in browsers Save jsnewwindow.html and test in browsers Note: Try this EDIT: open('tyvindustries/about.html', 'newwin', 'scrollbars=yes, width=630, height=500, top=100, left=100'); Note: Try this EDIT: open('tyvindustries/about.html', 'newwin', 'scrollbars=yes, width=630, height=500, top=100, left=100');
36
CSW131 Steven Battilana 36 Hide and Show Elements [Back to INDEX] [Back to INDEX] [Back to INDEX] JavaScript can manipulate CSS properties dynamically – this is an example JavaScript can manipulate CSS properties dynamically – this is an example Use xhtml_doc$.html to create jsshowhide.html and on line after type Info This is the stuff I want to show on user mouseover. [any amount] Use xhtml_doc$.html to create jsshowhide.html and on line after type Info This is the stuff I want to show on user mouseover. [any amount] Then on the line after type function showinfo() { document.getElementById('showme').style.visibility = 'visible'; } function hideinfo() { document.getElementById('showme').style.visibility = 'hidden'; } there’s more… Then on the line after type function showinfo() { document.getElementById('showme').style.visibility = 'visible'; } function hideinfo() { document.getElementById('showme').style.visibility = 'hidden'; } there’s more…
37
CSW131 Steven Battilana 37 Hide and Show Elements (CONT.) [Back to INDEX] [Back to INDEX] [Back to INDEX] Then set the CSS formatting for #linksa and #showme on line before #links a { Then set the CSS formatting for #linksa and #showme on line before #links a { font-size: small; font-size: small; color: #999; color: #999; text-decoration: none; } #showme { font-size: small; background-color: #ccc; width: 300px; visibility: hidden; } text-decoration: none; } #showme { font-size: small; background-color: #ccc; width: 300px; visibility: hidden; } Save jsshowhide.html and test in browsers. Change drab CSS and review. Save jsshowhide.html and test in browsers. Change drab CSS and review. Note: This is an accessibility “plus”. Note: This is an accessibility “plus”.
38
CSW131 Steven Battilana 38 Swap Images [Back to INDEX] [Back to INDEX] [Back to INDEX] JavaScript is used to swap images, with a common example being pointing JavaScript is used to swap images, with a common example being pointing Use xhtml_doc$.html to create jsswapimage.html and on line after type there’s more… there’s more…
39
CSW131 Steven Battilana 39 Swap Images (CONT.) [Back to INDEX] [Back to INDEX] [Back to INDEX] Then on the line after type function swap(image, source) { document.getElementById(image).src = source; } function restore(image, source) { document.getElementById(image).src = source; } Then on the line after type function swap(image, source) { document.getElementById(image).src = source; } function restore(image, source) { document.getElementById(image).src = source; } Save and test jsswapimage.html to point to and see images switch Save and test jsswapimage.html to point to and see images switch (nospace) (no space)
40
CSW131 Steven Battilana 40 Notes, Use, Other Resources [Back to INDEX] [Back to INDEX] [Back to INDEX] This material is a simple preview of a number of JavaScript concepts and supplements the material covered in class and per the textbook. It is far from complete and used only as an introduction. This material is a simple preview of a number of JavaScript concepts and supplements the material covered in class and per the textbook. It is far from complete and used only as an introduction. There are countless JavaScript resources on the Internet and in print. Use them with discretion, as intended, and only when you understand how they work. There are countless JavaScript resources on the Internet and in print. Use them with discretion, as intended, and only when you understand how they work. In addition to material from the author, a number of resources were used for academic purposes, including the textbook, w3.org, w3cschools.com, and other textbook Internet web sites. In addition to material from the author, a number of resources were used for academic purposes, including the textbook, w3.org, w3cschools.com, and other textbook Internet web sites. This is an academic teaching aid and not for sale or resale by any means. This is an academic teaching aid and not for sale or resale by any means. Copyright © 2009-2012 Steven Battilana. 610.430.4198, sbattilana@wcupa.edu, CSC Dept., UNA 150, West Chester University, West Chester, PA 19383Steven Battilanasbattilana@wcupa.edu
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.