40
C S W 1 3 1 S t e v e n B a t t i l a n a 1 CSW 131 – Supplement 2 CSW 131 – Supplement 2 Working with Working with JavaScript JavaScript (NOT in Textbook) (NOT in Textbook) Prepared by Prof. B. for use in Prepared by Prof. B. for use in CSW 131 (Intro. To Web Design) CSW 131 (Intro. To Web Design) Index ght © 2009-2013 Steven Battilana . 610.430.4198, [email protected] , CSC Dept., UNA 150, West Chester University, West Chester, PA 19

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)

Embed Size (px)

Citation preview

Page 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)

CS

W1

31

Ste

ven

B

att

ilan

a

1

CSW 131 – Supplement CSW 131 – Supplement 22

Working with JavaScriptWorking with JavaScript(NOT in Textbook)(NOT in Textbook)

Prepared by Prof. B. for use inPrepared by Prof. B. for use inCSW 131 (Intro. To Web Design)CSW 131 (Intro. To Web Design)

Index

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383

Page 2: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 2

INDEX (use links to view topic – slide number is INDEX (use links to view topic – slide number is blackblack))

3 Some Key Things (But Not All) You Can Do With JavaScript & Simple Guidelines4 Write JavaScript (Text) to Your Web Document5 Using External JavaScript 6 Executing JavaScript In Blocks7 JavaScript Comments8 JavaScript Variables9 JavaScript Arithmetic Operators10 JavaScript Assignment Operators11 The + Operator Used on Strings and Combined with Numbers [1] 12 [2]13 Comparison and Logical Operators [1] 14 [2]15 Conditional Statements16 Conditional Statements: If 17 Conditional Statements: If…else 18 Conditional Statements: If…else if…else 1 of 2 19 2 of 2 20 Conditional Statements: Switch 1 of 2 21 2 of 222 Popup Boxes: Alert 23 Popup Boxes: Confirm 24 Popup Boxes: Prompt 25 More about functions26 Loops: for27 Loops: while28 Loops: do…while29 Loops: break Statement30 Loops: continue Statement31 Loops: for…in Statement40 40 Notes, Use, Other ResourcesNotes, Use, Other Resources

ExtrasExtras

32 32 Validate a Form 1 of 3Validate a Form 1 of 3 33 33 2 of 32 of 3 34 34 3 of 33 of 3

35 35 Open a New WindowOpen a New Window

36 36 Hide and Show Elements 1 of 2Hide and Show Elements 1 of 2 37 37 2 of 22 of 2

38 38 Swap Images 1 of 2 Swap Images 1 of 2 39 39 2 of 22 of 2

Important ReminderImportant Reminder

Use Use <!- -//- -><![CDATA[//><!- - & & //- -><!]]>

““wrapper” wrapper” ONLYONLY as needed (see slide 3). as needed (see slide 3).

Page 3: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 3

Some Key Things (But Not All) You Can Do With Some Key Things (But Not All) You Can Do With JavaScriptJavaScript

& Simple JavaScript Guidelines & Simple JavaScript Guidelines [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 or as external page)

Create small(er) programs within HTML pages Create event user-driven reactions Read and write 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 <head>, <body>, and or both

Simple Guidelines JavaScript is case sensitive: careful with capitalization! White space is ignored: so make it easily readable. Tags: opens <script type="text/javascript"><!- -//- -><!

[CDATA[//><!- -

closes //- -><!]]></script>

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” ONLY as needed (HTML5 should not be an

issue).

* “Wrapper” forces CDATA rather thanauto-XHTML #PCDATA (max compatibility)

Page 4: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 4

Write JavaScript (Text) to Your Web DocumentWrite JavaScript (Text) to Your Web Document[Back to INDEX]

document.writedocument.write precedes precedes ("what you want to write to your web ("what you want to write to your web document");document");

Download Download supp2.zipsupp2.zip from our Hot! Page. After extracting the from our Hot! Page. After extracting the files, open files, open default$$.htmldefault$$.html. On two new lines before . On two new lines before </head> </head> type:type:<script type="text/javascript"><script type="text/javascript"> [required OPEN tag][required OPEN tag]</script></script> [required CLOSE tag] [required CLOSE tag] Save file as Save file as defaultJS.htmldefaultJS.html..

BETWEEN the above two lines type this code:BETWEEN the above two lines type this code: document.write("Text for my web page document");document.write("Text for my web page document"); Save file as Save file as write_js_text.htmlwrite_js_text.html and view it. and view it.

You can also You can also add HTML within the JavaScript add HTML within the JavaScript by editing the by editing the code:code:

document.write("document.write("<h1><h1>Text for my web page documentText for my web page document</h1></h1>");");

Save file again and view it. Save file again and view it. Stop JavaScript from showing as page content when it is Stop JavaScript from showing as page content when it is

deactivateddeactivated

<!-- <!-- [using HTML comment tags][using HTML comment tags] <script type="text/javascript“>[some Javascript]</script> <script type="text/javascript“>[some Javascript]</script> -->-->

Save again and view.Save again and view.

Page 5: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 5

Using External JavaScriptUsing External JavaScript[Back to INDEX]

You can You can use the same JavaScript on several pagesuse the same JavaScript on several pages by by referring to an external pagereferring to an external page using this format: using this format:

<head><head><script type="text/javascript" src="xyz.js"></script><script type="text/javascript" src="xyz.js"></script></head></head>

((xyzxyz can be any name) can be any name)

Page 6: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 6

Executing JavaScript In BlocksExecuting JavaScript In Blocks[Back to INDEX]

JavaScript can be grouped in blocks using curly bracesJavaScript 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 This is used to a large extend for functionsfunctions and and conditionsconditions, ,

which we will get into shortly.which we will get into shortly.

Page 7: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 7

JavaScript CommentsJavaScript Comments[Back to INDEX]

Single line commentsSingle line comments::

<script type="text/javascript"><script type="text/javascript">// Write a heading// Write a headingdocument.write("<h1>This is a heading</h1>");document.write("<h1>This is a heading</h1>");</script></script>

Multi-line commentsMulti-line comments: :

<script type="text/javascript"><script type="text/javascript">/*/*The code below should be executedThe code below should be executedfor the upcoming holiday sale only!for the upcoming holiday sale only!*/*/[assume valid script is written here];</script></script>

Comments used at end of a line of codeComments used at end of a line of code::

<script type="text/javascript"><script type="text/javascript">document.write("<h1>The heading</h1>"); document.write("<h1>The heading</h1>"); // main heading// main heading</script></script>

Page 8: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 8

JavaScript VariablesJavaScript Variables[Back to INDEX] [Back to INDEX]

VariablesVariables can be declared WITH or WITHOUT valuescan be declared WITH or WITHOUT values

var x;var x; [variable x [variable x WITHOUTWITHOUT a declared value] a declared value]

var xvar x=7=7;; [variable x [variable x WITHWITH a declared value of 7] a declared value of 7]

Page 9: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 9

JavaScript Arithmetic OperatorsJavaScript Arithmetic Operators[Back to INDEX] [Back to INDEX]

JavaScript JavaScript ArithmeticArithmetic Operators Operators Arithmetic operators are Arithmetic operators are used to perform arithmetic used to perform arithmetic

between variables and/or values.between variables and/or values. Given that Given that y=5y=5, the table below explains the arithmetic , the table below explains the arithmetic

operators:operators:+ Addition x=y+2 x=7- Subtraction x=y-2 x=3* Multiplication x=y* 2 x=10/ Division x=y/ 2 x=2.5% Modulus (division remainder) x=y% 2 x=1

++ Increment x=++y x=6-- Decrement x=--y x=4

+1 for Increment; -1 forDecrement

x=5/ 2 resulting in 2 with a remainder of 1

Page 10: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 10

JavaScript Assignment OperatorsJavaScript Assignment Operators[Back to INDEX] [Back to INDEX]

JavaScript JavaScript AssignmentAssignment Operators Operators Assignment operators are Assignment operators are used to assign values used to assign values to to

JavaScript variables.JavaScript variables. Given that Given that x=10x=10 and and y=5y=5, the table below explains the , the table below explains the

assignment operators :assignment operators :

Operator Example Same As Result= x=y x=5+= x+=y x=x+y x=15-= x-=y x=x-y x=5* = x* =y x=x* y x=50/ = x/ =y x=x/ y x=2% = x% =y x=x% y x=0 No remainder (Modulus)No remainder (Modulus)

Page 11: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 11

The + Operator Used on Strings The + Operator Used on Strings and Combined with Numbers and Combined with Numbers [Back to INDEX] [Back to INDEX]

Using the Using the ++ operator on text strings operator on text strings concatenates the concatenates the stringsstrings

So if:So if:txt1= "I’ll earn a";txt1= "I’ll earn a";

txt2= "good grade";txt2= "good grade";

txt3=txt1+txt2;txt3=txt1+txt2;

becomes becomes I’ll earn agood gradeI’ll earn agood grade

so add a space after so add a space after aa in txt1 orin txt1 or beforebefore goodgood in txt2in txt2

or or add a space add a space within txt3within txt3

txt3=txt1+txt3=txt1+"" ""+txt2;+txt2;

which correctly becomes which correctly becomes I’ll earn a good gradeI’ll earn a good grade

When the + operator is used combining strings + numbers When the + operator is used combining strings + numbers the result is always a string (of characters)the result is always a string (of characters): see the next : see the next page…page…

Page 12: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 12

The + Operator Used on Strings The + Operator Used on Strings and Combined with Numbers and Combined with Numbers (CONT.) [Back to (CONT.) [Back to

INDEX] INDEX] Try these combinations within a HTML document (Try these combinations within a HTML document (remembering remembering

the required start the required start <script type="text/javascript"> <script type="text/javascript"> and end and end </script></script> script tagsscript tags) starting on a new line before </head>:) starting on a new line before </head>:

__________Below are the results____________________Below are the results__________x=5+10;x=5+10;document.write(x); document.write(x); [result: addition with answer = 15][result: addition with answer = 15] document.write("<br />"); document.write("<br />"); [try without, then with these breaks][try without, then with these breaks]x="5"+"10";x="5"+"10";document.write(x); document.write(x); [result: concatenation with answer = 510][result: concatenation with answer = 510] document.write("<br />"); document.write("<br />"); x=5+"10";x=5+"10";document.write(x); document.write(x); [result: concatenation with answer = 510][result: concatenation with answer = 510] document.write("<br />"); document.write("<br />"); x="5"+10;x="5"+10;document.write(x); document.write(x); [result: concatenation with answer = 510][result: concatenation with answer = 510]

Save as Save as operator_example.html operator_example.html andand test test..

Page 13: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 13

Comparison and Logical OperatorsComparison and Logical Operators[Back to INDEX] [Back to INDEX]

ComparisonComparison operatorsoperators are are used in logical statements used in logical statements to to determine equality or difference between variables or valuesdetermine equality or difference between variables or values. .

Given Given that that x=5x=5, the table below explains the comparison , the table below explains the comparison operators:operators:

So a possible use would be:So a possible use would be:if (grade>=93) document.write("You earned an A!");if (grade>=93) document.write("You earned an A!");

(and also an example of why you would use document.write)(and also an example of why you would use document.write)

Operator Description Example== is equal to x==8 is false

x===5 is true

x==="5" is false!= is not equal x!=8 is true> is greater than x>8 is false< is less than x<8 is true>= is greater than or equal to x>=8 is false<= is less than or equal to x<=8 is true

=== is exactly equal to (value and type)

Page 14: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 14

Comparison and Logical Operators Comparison and Logical Operators (CONT.)(CONT.)[Back to INDEX] [Back to INDEX]

LogicalLogical operatorsoperators are used to determine the logic between are used to determine the logic between variables or values.variables or values.

GivenGiven that that x=6x=6 and and y=3y=3, the table below explains the logical , the table below explains the logical operators:operators:

JavaScript also contains a JavaScript also contains a conditionalconditional operatoroperator that that assigns a assigns a value to a variable based on some conditionvalue to a variable based on some condition, using this , using this syntax:syntax:

variablename=(condition)?value1variablename=(condition)?value1[if TRUE][if TRUE]:value2:value2[if FALSE][if FALSE]

So as an example for So as an example for greetinggreeting with the variable with the variable visitorvisitor::

greeting=(visitor=="PRES")?"Dear President ":"Dear ";greeting=(visitor=="PRES")?"Dear President ":"Dear ";

If If the variable the variable visitorvisitor has the value of " has the value of "PRESPRES“ (condition is “ (condition is TRUE), TRUE), ThenThen the variable the variable greetinggreeting will be assigned the value will be assigned the value ""Dear President Dear President " " ElseElse it will be assigned " it will be assigned "DearDear" (condition is FALSE)." (condition is FALSE).

Operator Description Example&& and (x < 10 && y > 1) is true| | or (x==5 | | y==5) is false! not !(x==y) is true

Page 15: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 15

Conditional StatementsConditional Statements[Back to INDEX] [Back to INDEX]

ConditionalConditional statements are used to perform different statements are used to perform different actions based on different conditions. Your code can do the actions based on different conditions. Your code can do the following: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…

Page 16: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 16

Conditional Statements: Conditional Statements: IfIf (CONT.)(CONT.)[Back to INDEX] [Back to INDEX]

An An if statement if statement uses this syntax:uses this syntax:if (if (conditioncondition)){{code to be executed if condition is truecode to be executed if condition is true} }

So as an example for when this So as an example for when this specific condition specific condition is is truetrue::

<script type="text/javascript"><script type="text/javascript">//Write a "Good morning" greeting if//Write a "Good morning" greeting if//the time is less than 12 noon//the time is less than 12 noon

var d=new Date();var d=new Date(); [commonly used [commonly usedvar time=d.getHours();var time=d.getHours(); variables]variables]

if (time<12)if (time<12)  {  {  document.write("<b>Good morning!</b>");  document.write("<b>Good morning!</b>");  }  }</script></script>

Returning greeting as appropriate (and Returning greeting as appropriate (and easy to changeeasy to change)) Save as Save as cond_statement_if.htmlcond_statement_if.html

Page 17: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 17

Conditional Statements: Conditional Statements: If…elseIf…else (CONT.)(CONT.)[Back to INDEX] [Back to INDEX]

An An if…else statement if…else statement uses this syntax:uses this syntax: if ( if (conditioncondition))    {{    code to be executed if condition is truecode to be executed if condition is true    }} else else   {{

code to be executed if condition is not truecode to be executed if condition is not true   }}

So So editedit the if example in the if example in cond_statement_if.html cond_statement_if.html ::

if (time < 12)if (time < 12)  {  {  document.write("Good morning!");  document.write("Good morning!");  }  }elseelse  {  {  document.write("Good day!...I said good day!!!");  document.write("Good day!...I said good day!!!");  }  }

Returning 1 of 2 greetings (again Returning 1 of 2 greetings (again easy to changeeasy to change)) Save as Save as cond_statement_if…else.htmlcond_statement_if…else.html

Page 18: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 18

Conditional Statements: Conditional Statements: If…else if…elseIf…else if…else 1 of 1 of 2 2 (CONT.)(CONT.)

[Back to INDEX] [Back to INDEX] An An if…else if…else statement if…else if…else statement uses this syntax:uses this syntax:

if (if (condition1condition1))  {  {    code to be executed if condition1 is truecode to be executed if condition1 is true  }  }else if (else if (condition2condition2))  {  {    code to be executed if condition2 is truecode to be executed if condition2 is true  }  }elseelse  {  {    code to be executed if condition1 and condition2 are not code to be executed if condition1 and condition2 are not truetrue  }  }

Page 19: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 19

Conditional Statements: Conditional Statements: If…else if…elseIf…else if…else 2 of 2 of 2 2 (CONT.)(CONT.)

[Back to INDEX] [Back to INDEX] So So here is a good all day user greeting script here is a good all day user greeting script using this code:using this code:

<script type="text/javascript"><script type="text/javascript">var d = new Date();var d = new Date();var time = d.getHours();var time = d.getHours();if (time<12)if (time<12) { { document.write("<b>Good morning</b>"); document.write("<b>Good morning</b>"); } }else if (time<18) //or time>12 && <18else if (time<18) //or time>12 && <18 { { document.write("<b>Good afternoon</b>"); document.write("<b>Good afternoon</b>"); } }elseelse { { document.write("<b>Good evening</b>"); document.write("<b>Good evening</b>"); } }</script> </script>

Returning 1 of several greetings (again Returning 1 of several greetings (again easy to changeeasy to change)) Save as Save as cond_statement_if…else_if…else.htmlcond_statement_if…else_if…else.html

Page 20: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 20

Conditional Statements: Conditional Statements: SwitchSwitch 1 of 2 1 of 2 (CONT.)(CONT.)[Back to INDEX] [Back to INDEX]

Use the Use the switch statement switch statement to select one of many blocks of to select one of many blocks of code to be executedcode to be executed. Following is the syntax:. Following is the syntax:

switch( switch(n . . . i.e., var being switchedn . . . i.e., var being switched)){{case case 1:1:    execute code block 1execute code block 1  break;  break;case case 22:: [allows use of as many cases as needed] [allows use of as many cases as needed]    execute code block 2execute code block 2  break;  break;defaultdefault::    code to be executed if n is different from case 1 and 2code to be executed if n is different from case 1 and 2}}

How it works: First the single expression How it works: First the single expression nn (most often a (most often a variable), variable), is evaluated onceis evaluated once. The value of the expression is . The value of the expression is then compared with the values for each case in the then compared with the values for each case in the structurestructure. . If there is a match, the block of code associated If there is a match, the block of code associated with that case is executedwith that case is executed. . Using break stops code from running the next case

automatically.

Page 21: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 21

Conditional Statements: Conditional Statements: SwitchSwitch 2 of 2 2 of 2 (CONT.)(CONT.)[Back to INDEX] [Back to INDEX]

Switch code example. Note all or some cases may be used (again Switch code example. Note all or some cases may be used (again easy easy to changeto change). :). :

<script type="text/javascript"><script type="text/javascript">//You will receive a different greeting based on what day//You will receive a different greeting based on what day//it is. Note that Sunday=0, Monday=1, Tuesday=2, etc.//it is. Note that Sunday=0, Monday=1, Tuesday=2, etc.

var d=new Date();var d=new Date();var theDay=d.getDay();var theDay=d.getDay();switch (theDay)switch (theDay){{case 5:case 5:  document.write("Finally Friday");  document.write("Finally Friday");  break;  break;case 6:case 6:  document.write("Super Saturday");  document.write("Super Saturday");  break;  break;case 0:case 0:  document.write("Sleepy Sunday");  document.write("Sleepy Sunday");  break;  break;default:default:  document.write("I'm REALLY looking forward to this weekend!");  document.write("I'm REALLY looking forward to this weekend!");}}</script></script>

Save as Save as cond_statement_switch.htmlcond_statement_switch.html

Page 22: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 22

Popup Boxes: Popup Boxes: AlertAlert 1 of 3 1 of 3[Back to INDEX] [Back to INDEX]

Open Open defaultJS.htmldefaultJS.html and on line before and on line before </head> </head> type ONLY the type ONLY the 3 BLACK lines:3 BLACK lines: <script type="text/javascript"><script type="text/javascript">

function showalert() function showalert() [use a logical function name][use a logical function name]{{alert("Hello, world!");alert("Hello, world!");}}</script></script>

SaveSave asas jsalert_event.htmljsalert_event.html, and view in browser., and view in browser. To give To give useruser control, use an control, use an event handler event handler preceded by a preceded by a

functionfunction:: Type in green lines above (using showalert as function),

then on the line after the <body> tag type an opening form tag<form method="post" action="">and create a button to enable the event<p><button type="button" name="callscript" onclick="showalert();">Show the alert</button></p></form>

SaveSave asas jsalert_event.htmljsalert_event.html, view in browser, and try button., view in browser, and try button.

Page 23: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 23

Popup Boxes: Popup Boxes: ConfirmConfirm 2 of 3 2 of 3[Back to INDEX] [Back to INDEX]

Unlike an Alert Box, a Unlike an Alert Box, a Confirm Box Confirm Box enables a user to accept a condition enables a user to accept a condition by clicking OK (true) or declining by clicking Cancel (or X for false)by clicking OK (true) or declining by clicking Cancel (or X for false). .

Edit the existing code in Edit the existing code in jsalert_event.html jsalert_event.html on line after on line after </title> </title> <script type="text/javascript"><script type="text/javascript">

function showalert function showalert showconfirmshowconfirm() () [again, use a logical [again, use a logical function name] function name]

{{var r=confirm("Please click OK to accept or Cancel to var r=confirm("Please click OK to accept or Cancel to

decline");decline");if (r=if (r= =true)=true) { { document.write("Thank you for accepting our terms!"); document.write("Thank you for accepting our terms!"); } }elseelse document.write("Sorry, but you have declined our document.write("Sorry, but you have declined our

terms.");terms."); alert("Hello, world!"); alert("Hello, world!");}}</script></script>

Then in the Then in the <body> <body> edit the button to enable the eventedit the button to enable the event<p><button type="button" /name="callscript" onclick="<p><button type="button" /name="callscript" onclick="showalert showalert showconfirmshowconfirm();"> ();"> [using the same function name as above] [using the same function name as above] Show the alert Show the alert our terms of useour terms of use</button></p></button></p></form></form>

Save these changes as the file Save these changes as the file jsconfirm.html jsconfirm.html andand test it test it in your browser.in your browser.

Page 24: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 24

Popup Boxes: Popup Boxes: Prompt Prompt 3 of 33 of 3[Back to INDEX] [Back to INDEX]

A A Prompt Box Prompt Box lets you have user input a value before entering a page. When a lets you have user input a value before entering a page. When a prompt box pops up, prompt box pops up, the user will have to click either "OK", which returns the user will have to click either "OK", which returns their input value, or "Cancel" (returning no value) to proceed after entering their input value, or "Cancel" (returning no value) to proceed after entering an input valuean input value. .

Edit the existing code in Edit the existing code in jsconfirm.htmljsconfirm.html on line after on line after </title> </title> <script type="text/javascript"> <script type="text/javascript">function showconfirmfunction showconfirm showprompt showprompt ()(){{var r=confirm("Please OK to accept or Cancel to decline");var r=confirm("Please OK to accept or Cancel to decline");var name=prompt("Please enter your name","(type your name here)");var name=prompt("Please enter your name","(type your name here)");if (r==true)if (r==true)if (name!=null && name!="")if (name!=null && name!="") { { document.write("Thank you for accepting our terms!"); document.write("Thank you for accepting our terms!"); document.write("Thank you " + name + ", for signing in! You're in for a treat.");document.write("Thank you " + name + ", for signing in! You're in for a treat."); } }elseelse document.write("Sorry, but you have declined our terms."); document.write("Sorry, but you have declined our terms.");}}</script></script>

Then in the Then in the <body> <body> edit the button to enable the eventedit the button to enable the event<p><button type="button" /name="callscript" <p><button type="button" /name="callscript" onclick="onclick="showshowconfirmconfirmpromptprompt();">();">Show the our terms of use Show the our terms of use sign in promptsign in prompt</button></p></button></p></form></form>

Save these changes as Save these changes as jsprompt.html jsprompt.html andand test it test it in your browser.in your browser.

Page 25: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 25

More about More about functionsfunctions[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 <head> or <body> of a web page, but to ensure

your functions are loaded, in most cases place them in the <head> 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 <body>

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: <script type="text/javascript">function product(a,b){return a*b;}</script>

In body: <script type="text/javascript">document.write(product(17,7));</script>

Page 26: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 26

Loops: Loops: for for 1 of 61 of 6[Back to INDEX] [Back to INDEX]

Writing code using a Writing code using a looploop allows the same block of code to run allows the same block of code to run over and over againover and over again with conditions you set instead of voluminous with conditions you set instead of voluminous code.code.

In JavaScript, there are two different kind of loops:In JavaScript, there are two different kind of loops: for - loops through a block of code for a set number of timesloops through a block of code for a set number of times while - loops through a block of code while a set condition is loops through a block of code while a set condition is

truetrue forfor syntax: syntax: for for

(var=startvalue;var<=endvalue;var=var+increment)(var=startvalue;var<=endvalue;var=var+increment){{your codeyour code}}

Example: (place code in <body> of a HTML fileExample: (place code in <body> of a HTML file<script type="text/javascript"><script type="text/javascript">var i=0;var i=0;for (for (i=0i=0;;i<=5i<=5;;i++i++) ) [[start start endend incrementincrement]]{{document.write("The number is " + i);document.write("The number is " + i);document.write("<br />");document.write("<br />");}}</script></script>

Save as Save as jsforloop.htmljsforloop.html and and testtest in browser. in browser.

any comparing statementany comparing statement

Page 27: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 27

Loops: Loops: while while 2 of 62 of 6[Back to INDEX] [Back to INDEX]

As noted earlier, writing code using a As noted earlier, writing code using a while loopwhile loop allows the allows the same block of code to run over and over again while a set same block of code to run over and over again while a set condition is truecondition is true

whilewhile syntax: syntax: while (var<=endvalue)while (var<=endvalue){{your codeyour code}}

Example: (place code in <body> of a HTML fileExample: (place code in <body> of a HTML file<script type="text/javascript"><script type="text/javascript">var i=0;var i=0;while (i<=5) while (i<=5) [try switching the 5 to 15][try switching the 5 to 15]   {   {  document.write("The number is " + i);  document.write("The number is " + i);  document.write("<br />");  document.write("<br />");  i++;  i++; } }</script></script>

Save as Save as jswhileloop.htmljswhileloop.html and and testtest in browser. in browser.

any comparing statementany comparing statement

Page 28: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 28

Loops: Loops: do…while do…while 3 of 63 of 6[Back to INDEX] [Back to INDEX]

The The do…while loopdo…while loop is a while loop variant. is a while loop variant. It executes the code It executes the code once, then repeats the loop while a set condition is trueonce, then repeats the loop while a set condition is true

do…whiledo…while syntax: syntax: dodo { {

[first runs once][first runs once] your codeyour code } } while (var<=endvalue) while (var<=endvalue)

Example: (place code in <body> of a HTML fileExample: (place code in <body> of a HTML file<script type="text/javascript"><script type="text/javascript"> var i=0; var i=0;dodo  {  {  document.write("The number is " + i);  document.write("The number is " + i);  document.write("<br />");  document.write("<br />");  i++;  i++;  }  }while (i<=5); while (i<=5); </script></script>

Save as Save as jsdowhileloop.htmljsdowhileloop.html and and testtest in browser. in browser.

any comparing statementany comparing statement

Page 29: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 29

Loops: Loops: break break Statement 4 of 6Statement 4 of 6[Back to INDEX] [Back to INDEX]

The The breakbreak statement statement will break the loop and continue will break the loop and continue executing the code that follows after the loop executing the code that follows after the loop (if any).(if any).

Example: (place code in <body> of a HTML fileExample: (place code in <body> of a HTML file

<script type="text/javascript"><script type="text/javascript">var i=0;var i=0;for (i=0;i<=10;i++)for (i=0;i<=10;i++)  {  {  if (i==3)  if (i==3)    {    {

        break; break; [loop stops here, when var i = 3][loop stops here, when var i = 3]    }    }  document.write("The number is " + i);  document.write("The number is " + i);  document.write("<br />");  document.write("<br />");  }  }</script></script>

Save as Save as jsbreakloop.htmljsbreakloop.html and and testtest in browser. in browser. NoteNote: loop : loop stops at 3stops at 3; since no code is after the loop, ; since no code is after the loop,

script ends.script ends.

any comparing statementany comparing statement

Page 30: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 30

Loops: Loops: continue continue Statement 5 of 6Statement 5 of 6[Back to INDEX] [Back to INDEX]

The The continuecontinue statement statement will will breakbreak the current loop AND the current loop AND continue with the next value.continue with the next value.

Example: (place code in <body> of a HTML fileExample: (place code in <body> of a HTML file

<script type="text/javascript"><script type="text/javascript">var i=0var i=0for (i=0;i<=10;i++)for (i=0;i<=10;i++)  {  {  if (i==3)  if (i==3)    {    {

        continuecontinue; ; [loop stops when var i = 3, then [loop stops when var i = 3, then continues] continues]

    }    }  document.write("The number is " + i);  document.write("The number is " + i);  document.write("<br />");  document.write("<br />");  }  }</script></script>

Save as Save as jscontinueloop.htmljscontinueloop.html and and testtest in browser. in browser. NoteNote: loop : loop omits 3omits 3, but unlike break, , but unlike break, continuescontinues then then

through end (10)through end (10)

any comparing statementany comparing statement

Page 31: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 31

Loops: Loops: for…in for…in Statement 6 of 6Statement 6 of 6[Back to INDEX][Back to INDEX]

The The for...in for...in statement statement loops through the elements of an array or loops through the elements of an array or through the properties of an object.through the properties of an object.

for…infor…in syntax: syntax: for (for (variablevariable in in objectobject))    {{

    code to be executedcode to be executed    }}

Example: (place code in <body> of a HTML fileExample: (place code in <body> of a HTML file<script type="text/javascript"><script type="text/javascript">var x;var x;var stooges = new Array();var stooges = new Array();stooges[0] = "Moe";stooges[0] = "Moe";stooges[1] = "Larry";stooges[1] = "Larry";stooges[2] = "Curly";stooges[2] = "Curly";

for (x in stooges)for (x in stooges)  {  {  document.write(stooges[x] + "<br />");  document.write(stooges[x] + "<br />");  }  }</script></script>

Save as Save as jsforinloop.htmljsforinloop.html and and testtest in browser. in browser. We MUST really add "Shemp ", save and test again!We MUST really add "Shemp ", save and test again!

Page 32: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 32

Validate a FormValidate a Form[Back to INDEX][Back to INDEX]

JavaScript treats JavaScript treats document objects as a child document objects as a child and and uses dot notationuses dot notation valuevalue is assessed is assessed at the end at the end of the statementof the statement Conditional statements use if statements followed by the true codeConditional statements use if statements followed by the true code, ,

and and else can be used if false code is neededelse can be used if false code is needed = == = is used to test for equality is used to test for equality, while , while =!=! tests for inequality tests for inequality Open Open contact.html contact.html inin gophercoform gophercoform folder,folder, and on line before and on line before

</head> </head> typetype<script type="text/javascript"><script type="text/javascript">function validateform() function validateform() [a logical variable name we have created][a logical variable name we have created]{{ [here we are setting conditions if users leave fields blank][here we are setting conditions if users leave fields blank] if(document.contactform.firstname.value = = "") if(document.contactform.firstname.value = = "") { { [this happens if true][this happens if true] } } if(document.contactform.lastname.value = = "")if(document.contactform.lastname.value = = "") {{ [this happens if true][this happens if true] }} if(document.contactform.email.value = = "")if(document.contactform.email.value = = "") {{ [this happens if true] [this happens if true] }}}}</script></script> there’s more…there’s more…

(no(no space)space)

Page 33: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 33

Validate a Form Validate a Form (CONT.)(CONT.)[Back to INDEX][Back to INDEX]

Set message boxes regarding errors and create a Set message boxes regarding errors and create a variablevariable ((varvar) to help count ) to help count errors:errors:<script type="text/javascript"><script type="text/javascript">function validateform()function validateform(){{ var error = ""; var error = ""; [var name you create is [var name you create is error error in this case]in this case] if(document.contactform.firstname.value = = "")if(document.contactform.firstname.value = = "") {{

error = error + "Please enter your first name\n"; error = error + "Please enter your first name\n"; [\n=new line][\n=new line] } } if(document.contactform.lastname.value = = "") if(document.contactform.lastname.value = = "") { {

error = error + "Please enter your last name\n";error = error + "Please enter your last name\n"; }} if(document.contactform.email.value = = "") if(document.contactform.email.value = = "") {{

error = error + "Please enter your email\n";error = error + "Please enter your email\n"; } } if(error == "")if(error == "") [if there are NO errors][if there are NO errors]

{{

return true;return true; [form is submitted with no errors][form is submitted with no errors]

} else {} else {

alert(error);alert(error); [alert message appears with appropriate error messages][alert message appears with appropriate error messages]

return false;return false;

}}}} there’s more…there’s more…

Page 34: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 34

Validate a Form Validate a Form (CONT.)(CONT.)[Back to INDEX][Back to INDEX]

Finally, edit the Finally, edit the <form <form tag accordingly (on one line):tag accordingly (on one line):

<form action=" http://www.example.com" method="post" <form action=" http://www.example.com" method="post" name="contactform" name="contactform" onsubmit="return validateform();"onsubmit="return validateform();">> [user event ][user event ]

Save Save contact.htmlcontact.html and test submitting form with various and test submitting form with various text fields empty.text fields empty.

Page 35: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 35

Open a New WindowOpen a New Window[Back to INDEX][Back to INDEX]

JavaScript can create the dreaded, misused pop-up window (ads), but JavaScript can create the dreaded, misused pop-up window (ads), but used properly (i.e., Help, etc.) they are usefulused properly (i.e., Help, etc.) they are useful

openopen starts a new window, which starts a new window, which should be a user initiated eventshould be a user initiated event Use Use defaultJS.html defaultJS.html to create to create jsnewwindow.htmljsnewwindow.html, make title , make title Opening a Opening a

New WindowNew Window, then on the line before , then on the line before </head> </head> typetype<script type="text/javascript"><script type="text/javascript">function openwin() function openwin() [our logically named function][our logically named function]{{

open('DONE/gopherco/about.html', 'newwin');open('DONE/gopherco/about.html', 'newwin'); [use any file][use any file]}}</script></script>then on the line after then on the line after <body> <body> typetype<form method="post" action="" name="myform"> <form method="post" action="" name="myform"> <p><p><button type="button" name="popup" onclick="openwin();">Open <button type="button" name="popup" onclick="openwin();">Open Window</button>Window</button></p></p></form></form>

Save Save jsnewwindow.htmljsnewwindow.html and test in browsersand test in browsers Note: Try this EDIT:Note: Try this EDIT:

open(‘gopherco/about.html', 'newwin'open(‘gopherco/about.html', 'newwin', 'scrollbars=yes, width=630, , 'scrollbars=yes, width=630, height=500, top=100, left=100'height=500, top=100, left=100'););

Page 36: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 36

Hide and Show ElementsHide and Show Elements[Back to INDEX][Back to INDEX]

JavaScript can manipulate CSS properties dynamically – this is an JavaScript can manipulate CSS properties dynamically – this is an exampleexample

Use Use defaultJS.html defaultJS.html to createto create jsshowhide.html jsshowhide.html and on line after and on line after <body> <body> typetype<div id="links"><div id="links"><a href="javascript:;" onmouseover="showinfo();"<a href="javascript:;" onmouseover="showinfo();"onmouseout="hideinfo();">Info</a>onmouseout="hideinfo();">Info</a></div></div>

<div id="showme"><div id="showme">This is the stuff I want to show on user mouseover. This is the stuff I want to show on user mouseover. [any amount] [any amount] </div></div>

Then on the line after Then on the line after </title> </title> typetype<script type="text/javascript"><script type="text/javascript">function showinfo()function showinfo(){{ document.getElementById('showme').style.visibility = 'visible'; document.getElementById('showme').style.visibility = 'visible';}}function hideinfo()function hideinfo(){{ document.getElementById('showme').style.visibility = 'hidden'; document.getElementById('showme').style.visibility = 'hidden';}}</script></script> there’s there’s more…more…

Page 37: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 37

Hide and Show Elements Hide and Show Elements (CONT.)(CONT.)[Back to INDEX][Back to INDEX]

Then set the CSS formatting for Then set the CSS formatting for #links a #links a and and #showme #showme on line on line before before </head></head><style type="text/css"><style type="text/css">

#links a#links a{{

font-size: small;font-size: small;

color: #999;color: #999; text-decoration: none;text-decoration: none;

}}

#showme#showme{{font-size: small;font-size: small;background-color: #ccc;background-color: #ccc;width: 300px;width: 300px;visibility: hidden;visibility: hidden;}}

</style></style>

Save Save jsshowhide.htmljsshowhide.html and test in browsers. and test in browsers. Change drab CSS and Change drab CSS and reviewreview..

Note: This is an accessibility “plus” .Note: This is an accessibility “plus” .

Page 38: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 38

Swap ImagesSwap Images[Back to INDEX][Back to INDEX]

JavaScript is used to JavaScript is used to swap imagesswap images, with a common example being , with a common example being pointingpointing

Use Use defaultJS.html defaultJS.html to createto create jsswapimage.html jsswapimage.html and on line after and on line after <body> <body> typetype

<div id="images"><div id="images">

<a href="../gopherco/contact.html" onmouseover="swap <a href="../gopherco/contact.html" onmouseover="swap ('contactimage','gopherco/images/contact_off.gif');"('contactimage','gopherco/images/contact_off.gif');"onmouseout="restore('contactimage',‘gopherco/images/onmouseout="restore('contactimage',‘gopherco/images/contact_on.gif');">contact_on.gif');">

<img src="gopherco/images/contact_on.gif" alt="Contact" id= <img src="gopherco/images/contact_on.gif" alt="Contact" id= "contactimage" /></a>"contactimage" /></a>

</div></div>

there’s more…there’s more…

Page 39: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 39

Swap Images Swap Images (CONT.)(CONT.)[Back to INDEX][Back to INDEX]

Then on the line after Then on the line after <title><title> typetype<script type="text/javascript"><script type="text/javascript">function swap(image, source)function swap(image, source){{ document.getElementById(image).src = source; document.getElementById(image).src = source;}}function restore(image, source)function restore(image, source){{ document.getElementById(image).src = source; document.getElementById(image).src = source;}}</script></script>

Save and test Save and test jsswapimage.htmljsswapimage.html to point to and see images switchto point to and see images switch

(no(no space)space)

Page 40: 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)

CS

W1

31

Ste

ven

B

att

ilan

a

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383 40

Notes, Use, Other ResourcesNotes, Use, Other Resources[Back to INDEX] [Back to INDEX]

This material is a simple preview of a This material is a simple preview of a number of JavaScript concepts and number of JavaScript concepts and supplements the material covered in class supplements the material covered in class and per the textbook. It is far from complete and per the textbook. It is far from complete and used only as an introduction.and used only as an introduction.

There are countless JavaScript resources on There are countless JavaScript resources on the Internet and in print. Use them with the Internet and in print. Use them with discretion, as intended, and only when you discretion, as intended, and only when you understand how they work.understand how they work.

A number of resources were used for A number of resources were used for academic purposes, including the w3.org, academic purposes, including the w3.org, w3cschools.com, and other textbook w3cschools.com, and other textbook Internet web sites.Internet web sites.

This is an academic teaching aid and not for This is an academic teaching aid and not for sale or resale by any means.sale or resale by any means.

Copyright © 2009-2013 Steven Battilana. 610.430.4198, [email protected], CSC Dept., UNA 150, West Chester University, West Chester, PA 19383