Java Script Making Web pages come alive Objectives
Java. Script Making Web pages come alive
Objectives • Be able to read Java. Script scripts • Be able to write Java. Script scripts
To See Examples • Open text editor • Create HTML page • Type in each example, save and view with browser
Static vs. Dynamic • Static – page appears exactly as it was encoded, nothing changes – only HTML • Dynamic – page changes (possibly in response to users actions) – Can’t be only HTML – Scripts
Scripts: server-side vs. client-side • Server-side – the first type possible on the Web – action occurs at the server • Client-side – handles user interaction – generally easier to implement – may be prepared and implemented offline – action occurs on the client side (browser) – Java. Script is the most common example
DHTML • • HTML-Document description-we did Java. Script- Client-side interaction-will do CSS- Style definition-beyond Dynamic HTML = HTML + CSS + scripts
Java. Script • Developed by Netscape to be simple, cross-browser scripting language for Web • Syntax based on ‘C’ - a good starting point to learn other programming languages • Java. Script is not Java • <script type="text/javascript"> …</script> enclose a Java. Script script
Write() • Java. Script’s output statement: document. write (“Text”); • Inside the <script> tag, we must output HTML document. write (“<p>Text<br/>text</p>”);
Hello World <html> <head><title>hello javascript</title></head> <body> <script > document. writeln ("Hello, World!"); </script> </body> </html> • Output?
What is the output? <html> <head><title>hello javascript</title></head> <body> <script > document. write ("Hello, n World"); document. write ("Hello, <br/>2 the World"); </script> </body> </html>
Why? • Hello, World. Hello, 2 the World the document. writeln() method preserves any line breaks in the text string.
Java. Script • Statements end with ; – Can often get away with omitting • Character strings enclosed in “ ” or ‘ ’ • Can include an external source file with the src attribute : <script src=“file_name. js”></script>
Java. Script Comments • // Ignore rest of line • /* Ignore everything enclosed */ • Don’t forget to end the comment
Objects • Java. Script is an Object Oriented Language. • Objects are things—nouns – They have attributes---adjectives • We call the attributes properties – They have actions---verbs • We call the actions methods– use ()
Objects • Use dot-notation to indicate that a method or a property belongs to an object. • Car analogy • document. write() • document. bg. Color • Recall: methods have ()
Objects • Java. Script objects include the HTML elements, window, document • last. Modified is a property of the document object.
Java. Script • A variable stores a value. – Declare a variable with the keyword var • Assignment: variable = value; • + adds numbers • + concatenates strings of characters e. g. “ab” + “cd” is “abcd” • last. Modified is a property of the document object.
Example <html> <head><title>Last Modified</title></head> <body> <script> var date; date=document. last. Modified; document. writeln ("This page was last modified: “ + date); </script> </body> </html> • Will automatically update. Output?
Output This page was last modified: 01/25/2005 12: 40: 18 • Note: var date=document. last. Modified; could have been in one line • See new window 2. html
Window • The document object is contained within a window object. • window has methods: – Alert () – Confirm () – Prompt () • window is assumed so • alert () is equivalent to window. alert ()
Alert() • Alert (“some string”) pops up a message box containing its string. • It is a method of the (assumed) window object.
Alert() <html> <head><title>hello alert</title></head> <body> <script> alert ("Hello, World!"); </script> </body> </html> • Output: alert box. Run it to see.
Confirm • Confirm uses if-else logic. true/false. Can I assume? • Declare a variable. • Confirm returns a value which you assign to a variable. O. K. button sends true. Cancel sends false. • Test the variable:
Confirm • <script> var x = confirm ("Are you sure you are ok? "); if (x) alert ("Good!"); else alert ("Too bad"); </script>
Prompt() method returns the text <script> var y=prompt ("please enter your name"); document. writeln (“Hello, ” + y); </script>
Prompt() • • You assign the result to a variable. You use the value. Optional: Second parameter to Prompt() Is the default value.
Equality • == tests for equality • A==B has the value true when A and B are the same; false otherwise. • != tests for inequality
Password <head> <script > var guess; var password=“fool”; guess=prompt(' enter password '); if (password!=guess) location=“forbidden. html”; </script> </head> • Why fool? …
Because… • Password is in source which may be viewed. • I must admit that I couldn’t view it!!
Events • Usually, user actions generate events that belong to objects. • mouseover • load • click
Event Handlers • Event handlers-respond to users actions – onmouseover – onmouseout – onload – onunload • Event handlers are put inside corresponding HTML tags. • Not inside <script>…</script>
Case on. Click="alert ('You clicked the button!'); " • The underlined parts are HTML • The quoted string is Java. Script • on. Click – The Java naming convention is easier to read. – This is fine in HTML, but an error if it occurs in Java. Script is case sensitive. HTML is not. • Please note: Since we have a quoted string inside another quoted string, we need both single and double quotes.
Event Handlers • Most HTML elements have the following event handlers: – on. Click -- the form element is clicked – on. Dbl. Click -- the form element is clicked twice in close succession – on. Mouse. Down -- the mouse button is pressed while over the form element – on. Mouse. Over -- the mouse is moved over the form element – on. Mouse. Out -- the mouse is moved away from the form element – on. Mouse. Up -- the mouse button is released while over the form element – on. Mouse. Move -- the mouse is moved • In Java. Script, these should be spelled in all lowercase
Change Color <html> <head><title>Change the Background Color</title></head> <body > <h 3><a href="#" on. Mouseover="document. bg. Color=‘blue'; " on. Mouseout ="document. bg. Color='white'; "> Move your cursor over this link to change background color to blue. </a></h 3> </body> </html>
On. Mouseover <a href="#" on. Mouseover="alert ('Ouch! I asked you not to click this link!'); "> Don't click this link!</a> • What’s the first thing you’ll do? • Aside: I typed this twice. One worked. One didn’t. I never figured out difference.
Status (skip) • The window object has the property status whose value is displayed in the status bar. • Change it only briefly cause need the info. ? <a href=“#" on. Mouseover="status='Hi there!'; return true; " on. Mouseout="status=' '; return true; "> Place your mouse here!</a>
Push Button • Object that has some effect when it is pushed: e. g. doorbell except traffic light • User defined (as opposed to which? ) • Has no default behavior. (what was…. ) • May have client side scripts associated with its event attributes. When an event occurs (e. g. , the user presses the button, releases it, etc. ), the associated script is triggered.
Buttons are contained in forms window document form text submit reset button
Button • type="button" This command declares the input to be a button. • value="Click Me" This will be the text people will see on the button. Write whatever you want your visitors to see. • name="button 1" You can give the button a name so you can refer to it.
Button event handler <form> <input type="button" value="See Some Text" name="button 2" on. Click="alert ('Some Text'); "> </form> • Recall: window is the assumed object.
Color buttons <form> <input type="button" value="Change to Yellow!" name="button. Y" on. Click="document. bg. Color='yellow‘; "> <input type="button" value="Change to White!" name="button. W" on. Click="document. bg. Color=‘white‘; "> </form>
open • open( ) is a method of the window object. • It opens a new window. open(“URL”); • You can use it inside an event handler. • I had to use window. open(). I don’t know why.
Open <form> <input type="button" name="button 1" value ="new" on. Click ="window. open('forbidden. html'); "> </form> <a href="#" on. Click ="window. open('forbidden. html'); "> open sesame</a>
Full featured window. open('http: //www. blah. com/blah', ‘title', 'width=400, height=200, toolbar=yes, location=yes, directories=yes, status=yes, m enubar=yes, scrollbars=yes, copyhistory=ye s, resizable=yes') ;
Functions • A function is a named piece of code that performs a task. Has () • Functions are put in <head> so they are loaded before the page displays. • Are executed only when invoked. • Body enclosed in{ } (called a block) • May have parameters in () (values used by the function to do its task).
Functions • Methods are similar to functions that belong to an object. • Functions are similar to methods that belong to the script. Placed in head so they are loaded before they are called. • An event handler should be very short – Many handlers call a function to do their job (delegate).
Examples • Function_wo_param • Simple calculator. html • Bgcolor_buttons_func. html – On slide, too • Mixed up – On slide, too
<! -- bgcolor_buttons what will happen? --> <html><head> <script> function yellow(){document. bg. Color='yellow'; } function white(){document. bg. Color='white'; } </script> </head> <body> <form> <input type="button" value="Change to. Yellow" name="button. Y“ on. Click=“yellow(); "> <input type="button" value="Change to White" name="button. W“ on. Click="white(); "> </form> </body></html>
<! -- mixed up. what will happen? --> <html><head> <script> function yellow(){document. bg. Color='yellow'; } function white(){document. bg. Color='white'; } </script> </head> <body> <form> <input type="button" value="Change to. Yellow" name="button. Y“ on. Click="white()"> <input type="button" value="Change to White" name="button. W“ on. Click="yellow()"> </form> </body></html>
Script in Head <head> <title>welcome!</title> <script > alert (‘Welcome!'); </script> </head> • This will display the alert before the page starts loading. It’ll disappear when page loads. A function would be called from the body and executed.
Debugging Your Java. Script Programs • Three types of errors: – Load-time errors (occurs when the script is loading) – Run-time errors (occurs when the being executed) – Logical errors (free from syntax and structural mistakes, but result in incorrect results)
Common Mistakes • You need to debug your program: fix the mistakes w/o adding new ones. • Common mistakes include: – Misspelling a variable name – Mismatched parentheses or braces – Mismatched quotes – Missing quotes – Using ( instead of [ or { – Using = in place of ==
Tips for Writing Good Java. Script Code • Use good layout to make your code more readable. Indent command blocks to make them easier to read and to set them off from other code • Use descriptive variable names to indicate the purpose of your variables • Be careful how you use uppercase and lowercase letters in your code, because Java. Script commands and names are case-sensitive
Tips for Writing Good Java. Script Code • Add comments to your code to document the purpose of each script • Initialize all variables at the top of your script and insert comments describing the purpose and nature of your variables • Create customized functions that can be reused in different scripts. Place your customized functions in external files to make them available to your entire Web site
Summary • Objects – Properties – Methods • • Variables Push buttons Events and handlers-inside HTML tags functions
Summary • Given an HTML file containing a script, you should be able to show the corresponding web page. • Given a web page, you should be able to show the corresponding HTML file.
- Slides: 56