Your Federal Quarterly Tax Payments are due April 15th Get Help Now >>

JavaScript by bE254Hf

VIEWS: 0 PAGES: 47

									       JavaScript


A World Wind Tour of JavaScript




                                  1
                          Objectives
   Introduction to JavaScript
    » JavaScript: Its Beginnings
         – Advantages and disadvantages
         – How differs from html and server side programs
    »   Working with JS and HTML tags.
    »   Running onload, when done, on an event
    »   Using JS objects
    »   Objects with properties and methods
    »   Using conditional tests




                                                            2
                  Competencies
   At end of unit be able to
    » Describe 3 times when javascript runs
    » Describe some of the capabilities of JavaScript
    » Write a JavaScript with conditional expression
    » Use a JavaScript program with variables and
      calculations


                  Competency             Common
                    Alert:               Problem
                    You need to
                    know this!            Area!
                                      People seem to forget this

                                                                   3
            JavaScript: Its Beginnings
   JavaScript developed by Netscape & initially called livescript.
   After Java came out, Netscape cut a deal with Sun to rename
    it to JavaScript (12/95).
    » They are separate, distinct languages. (Though JavaScript is simpler).

   Microsoft …
    » Came out with their own flavor of JavaScript called “Jscript”.
    » They also added support for VBScript in IE. Differences are minor.
   Eventually standardized …
    » JavaScript has been turned over to the European Computer
      Manufactures Association, and is now officially called ECMAScript
    » Both Netscape & IE4.0 and Netscape implement ECMAScript
      standard.




                                                                     4
         The “goods” on JavaScript
   JavaScript can be used to:
       1. perform simple client-side computations
             For example, add up total costs of shopping cart before it is
              submitted.
       2. facilitate dynamic and interactive Web page creation
            For example, do image roll overs, pop up windows
             on click, expand a menu.
       3. Verify HTML forms enhance HTML forms with data
         collections and form validation
       4. manipulate user cookies -




                                                                        5
      The “not so goods” on JavaScript
   JavaScript runs completely on Client machine
   It does NOT have:
        1. Any graphic capabilities
             E.g., cannot show a graph of survey results.
       2. Access to client (you PC) resources
             Cannot print, modifying PC files, or launching client
              applications.
       3. Access to any Web server resources
             E.g., cannot send email, write to file, write to
              database.




                                                                 6
    PHP/JavaScript Similarities and Differences
     What they have in common. Both languages can:
     1.   Be embedded in HTML documents
     2.   Cause dynamic content to be displayed (e.g., the current date)
     3.   Can be placed in external files and “included” into html files
     4.   Look more like a programming language than HTML
     What they DON‟T have in common:
     1.   The big difference … JavaScript runs 100% on client (i.e., PC). This
          means:
             A.   JavaScript stuff runs noticeably faster
                   (not dependent on Internet and Web Server)
             B.    PHP has access to Web Server resources (mail, databases, files)
     2. Using differences
          A. Writing JavaScript does NOT require a Web Server (but more
             concern about browser implementation differences).
          B. PHP‟s syntax is easier to write and understand for beginners.



                                                                             7
How JavaScript Pages are Run
      Your PC                                                                               WebServer
   (Internet connected)                                                                   (Internet connected)


    1. Web Browser        2. Se                                                     Web Server
                                  nd R
                                         eque
                                                  s t fo r                           Software
    Please Enter                                             PH P
                                                                    fi l e
    A
    Phone
                                                                                3. Receive
    Number
                                                                               request, find
                                                                             file and read it.
   Submit Erase

                                                                                                 4. Execute
                                                                                                    PHP
                                                                                                 statements


    7. Web Browser                                                                5. Send
     Web Browser                                                                  results
    Phone Query                                                                    back.
    Results:
                                                     es   u l ts
                                         e tu   rn R
    That is                       6. R
    John Doe's
    Phone
    Number

                                                                                        JavaScript does
                                                                                        not run here
               JavaScript is run here by the
               browser but just before HTML                                                                      8
                          Objectives
   Introduction to JavaScript
    » JavaScript: Its Beginnings
         – Advantages and disadvantages
         – How differs from html and server side programs
    »   Working with JS and HTML tags.
    »   Running onload, when done, on an event
    »   Using JS objects
    »   Objects with properties and methods
    »   Using conditional tests




                                                            9
          Adding JavaScript to HTML pages

JavaScript is added to HTML pages using the <script> tag.
   • usually placed in the HEAD or BODY of the document

        <script src=URL language=“JavaScript”></script>

                                                          If link to an external
        <script language=“JavaScript”>                    file (use .js suffix)
        <!--
              Javascript code
        //-->
        </script>                                         If embed JS within
                                                          HTML




                                                                      10
                  A Simple Example
<HTML>
   <HEAD>
   <TITLE> A Beginning Script </TITLE>
   </HEAD>                             These statements are run before HTML
   <BODY>                              document interpreted by browser
   <SCRIPT LANGUAGE="JavaScript">
      document.write ("Welcome to the wonderful world of JavaScript");
   </SCRIPT>
   </BODY>
   </HTML>
                          Within the javascript „mode‟ any output
                          to browswer needs to be within a
                          document.write output command




                                                                    11
           Where do you put it?
•Can add JavaScript to head or body of html document

•Functions are usually added to the head section
   • assures that the functions OK (parsed) by the time
   they are called.

•Non-functions usually put in body
  then can call and functions in head




                                                     12
                          Objectives
   Introduction to JavaScript
    » JavaScript: Its Beginnings
         – Advantages and disadvantages
         – How differs from html and server side programs
    »   Working with JS and HTML tags.
    »   Running onload, when done, on an event
    »   Using JS objects
    »   Objects with properties and methods
    »   Using conditional tests




                                                            13
             When does it run?

JavaScript can run
  1. as the page loads
  2. as soon as the page is finished loading
  3. in response to user input (remember the form
     button?)




                 Competency
                   Alert:
                   You need to
                            !
                    know this


                                                    14
            JavaScript that Runs as Page Loads
                                                                    Normal HTML code
<HTML><HEAD><TITLE>Document Object</TITLE>
</HEAD>                                      Enter JavaScript. Within the
<BODY bgColor=#ccccff>                       html body (in this case)
<CENTER>                                        document.write like print.
<H2>Document Object </H2>                        Get lastModified browser vrbl. . The + is
<SCRIPT language=JavaScript>                    catenation.
  document.write("This page was last modified on”
                   + document.lastModified);
</SCRIPT>
                                             Calls function to get current date and output
</CENTER></BODY></HTML>                      date




document.write("This page was last modified on” + document.lastModified);


Output this set of text (called a string)       Output the result of this ‘command’
                                                                               15
      JavaScript output (onload) is HTML input …
. The output of JavaScript statements is taken as HTML input...
<HTML>
 <HEAD><TITLE> A Beginning Script </TITLE>       Write these 2 messages
 </HEAD><BODY>
 <SCRIPT language=JavaScript>
   document.write ("<FONT Size=4>JavaScript commands are interpreted first</FONT>");
   document.write ("<BR> <FONT COLOR=BLUE>JS output often generates HTML</FONT>");
  </SCRIPT>
</BODY></HTML></HTML>




                                                                         16
   JavaScript that Runs when Loading Complete
<html> <head> <title> Java Example 2 </title> </head> <body onload=waitLittle()>
<font size=4 color=blue> welcome to my page </font>
<br>Here is my stuff
<br> <br>
                                  Run ‘allertMe’ code call          Run ‘waitLittle’ when
                                  after 5000 miliseconds            page is loaded
<script language="JavaScript">
function waitLittle()
{
        setTimeout( "alertMe()", 5000 );
}                                           Create a pop-up box with test as text
function alertMe()
{
        alert('test');
}
</script>                                    After 5000 milisecond pop-up
This is some text over here.
</body> </html>




                                                                            17
   JavaScript that Runs in Response to User Input

<html><head>
<script language="JavaScript">
<!--
function showTime()
{
        document.forms["getDate"].curTime.value =
                (new Date()).toLocaleString();
}
function alertme()                                 Set the value of the form variable curTime to
{                                                  the current time
        alert("Don't Do that");
}
//-->
</script>                                                   When click call showtime
</head>
<body style="background-color: #fffff0;">                             If they click generate an alert
<form name="getDate">
<input type="button" name="getTime" onClick="showTime()"
                value="Show Current Time" />
<input type="text" name="curTime" size="40" onClick="alertme()"/>
</form>




                                                                                          18
Dealing with Browsers that don’t Support JavaScript

You may have noticed something a little strange about the examples so far.

         <script language=“JavaScript”>
                <!--
                           Javascript code
                //-->
         </script>

This makes the script invisible to browsers that don’t support JavaScript by
        “commenting it out”. In addition, you can provide some page content
        that only displays when the browser DOESN’T handle JavaScript:

         <noscript>
                Your browser doesn‟t support Javascript
         </noscript>

The only limitation with this is that this will NOT be displayed by NS if the user
        has JavaScript just disabled.
                                                                           19
          Some Important Aspects of JavaScript


• Case Sensitive: Variable names, functions you use
    - (e.g., Date not date )
•Space Insensitive - generally ignored, except in strings
•Statements end in semicolon – Except JS will assume you meant to
semicolon at the end of the line if the statement appears to be
complete.




                                                         20
                          Objectives
   Introduction to JavaScript
    » JavaScript: Its Beginnings
         – Advantages and disadvantages
         – How differs from html and server side programs
    »   Working with JS and HTML tags.
    »   Running onload, when done, on an event
    »   Using JS objects
    »   Objects with properties and methods
    »   Using conditional tests




                                                            21
           JavaScript And Objects ...
   JavaScript is object-oriented
       – Objects are things your scripts can work with
              Have JS objects to work with browsers, windows, and forms
       – Objects have
              properties - are variables or other objects describing the object.
                 » E.g., document.lastmodified
      Object name                              Property has time value (like a date)

              methods - behaviors or built-in functions you use
                » E.g., accessed my ObjectName.MethodName()


                                                      Method name
                     Object name

                                                                         22
         Using JavaScript Objects …
   Lots of useful properties available
   Here are some properties for window object:
    » document.lastModified – (read-only property) gives the
      document last changed date
    » document.URL - (read-only property) gives the URL of the
      document source code file.
    » window.referrer – (read-only property) gives the URL of
      the calling document. (It is an empty string, if user does not
      reach the URL by clicking a link.
    » window.title – (read-only property) gives the value in
      the <TITLE> ... </TITLE> tag.


                                                           23
           Printing out one of these
Can use the plus sign (+) to attach
  string output with
 propert output

 document.write("last modified:”
                           + document.lastModified +
                                              "<P>");
Write the
following out.
               Print out this string

                 Attach to the string this property

                            Attach to the entire string this html tag
                                                           24
A couple other interesting properties
   Here are a few examples of properties
    » navigator.appName – Set to the browser name
    » window.location – the current URL your viewing. Setting
      this property to a URL will redirect the browser
       – window.location = „http://indelible-learning.com‟;
    » window.status – what is being displayed on the status line of
      the browser
    » navigator.appName – Name of browser running
    » document.title – the information in the <title> tag
    » document.lastModified – last modified time of document

                     Competency
                       Alert:
                       You need to
                                !
                        know this


                                                            25
                   For example
<HTML>
 <HEAD> <TITLE>Document Information Properties</TITLE>
 </HEAD>
 <BODY>
 <SCRIPT LANGUAGE="JavaScript">
 document.write("Referring link was:”
                   + document.referrer) + "<BR>")
 document.write("Document URL is:“ + document.URL +"<BR>")
 document.write("The title is: " + document.title +"<BR>")
 document. write("last modified:”
                        + document.lastModified + "</P>")
 </SCRIPT>
 <HR>
 This is my web site. It is my Web Site all by myself.
 </BODY>
 </HTML>




                                                       26
              Using an Object Method – date()

    The Date object to access time and date information.          Creates new date object
    Unlike the Math object, need to create a Date object first:
             var dateObj = new Date();

    You can specify the data/time when you create the object.
              xmasObj = new Date(“December, 25, 2002”);

    Can print out current date via:
              document.write ( new Date().toLocaleString());


<HTML><HEAD><TITLE>Document Object</TITLE>
</HEAD>
<BODY bgColor=#ccccff>
<CENTER>
<H2>Document Object </H2>
<SCRIPT language=JavaScript>

          document.write ( new Date().toLocaleString());
     </SCRIPT>
</CENTER></BODY></HTML>
                                                                                27
                              The Math Object


    An example JavaScript object.
     Math.abs(number)                 absolute value
     Math.sin(number)                 sine of an angle (expressed in radians)
     Math.cos(number)                 cosine of an angle (expressed in radians)
     Math.round(number)               closest integer value
     Math.ceil(number)                rounds up to next integer value
     Math.floor(number)               rounds down to next integer value
     Math.log(number)                 natural log of the number
     Math.sqrt(number)                square root of the number
     Math.random(number)              returns a floating point number
                                           that is >= 0.0 but < 1.0

Other methods include:
         tangent, arc tangent, arc sine, arc cosine, tangent, power, angle of polar
coordinates, maximum, and minimum.
Also has constant definitions for values like pi and e (natural log base).
                                                                                28
            Math Object Example
<HTML><HEAD><TITLE>Document Object</TITLE>
</HEAD>
<BODY>
<SCRIPT language=JavaScript>
 document.write( "<br> sqrt(25)=" + Math.sqrt(25));
 document.write( "<br> round(5.632)=" +Math.round(5.632));

 document.write( "<br> floor( 5.232 )=" + Math.floor( 5.232 ));

</SCRIPT>
</CENTER></BODY></HTML>




                                                                  29
                          Objectives
   Introduction to JavaScript
    » JavaScript: Its Beginnings
         – Advantages and disadvantages
         – How differs from html and server side programs
    »   Working with JS and HTML tags.
    »   Running onload, when done, on an event
    »   Using JS objects
    »   Objects with properties and methods
    »   Using conditional tests




                                                            30
        Competency
          Alert:
          You need to
          know this   !
                           Using Variables
                                                Each variable should
                                                be „defined‟ with
<HTML><HEAD><TITLE>Document Object</TITLE>      var
</HEAD>
<BODY bgColor=#ccccff>
<CENTER>                                                 Set variables x, y, z
<H2>Using Variables </H2>
<SCRIPT language=JavaScript>
         var x = 12;
         var y = 15;
         var z = y + x;                         Output a string, then a variable
         document.write( "x=" + x + "<br>");    and then <br> tag.
         document.write ( 'y='+ y + "<br>" );
         document.write ( 'z=' + z + "<br>");
     </SCRIPT>
</CENTER></BODY></HTML>
                                                        Note: remember to separate strings
                                                        from values with a plus sign


                                                                          Common
                                                                          Problem
                                                                           Area!
                                                                       People seem to forget this




                                                                                   31
           Some JavaScript Operators
Oper       Example           Result
+          X=2+z             Addition - X is assigned z plus 2

+ (strg)   Z = „a‟ + „b” ;   Catenation - Z is assigned „ab‟

-          y= 3 – 1;         Subtraction – y is assign 2;

*          y=2*apple;        Multiplication – y is assign 2 times apple


/          x = y / 2;        Division = z is assign y divided by 2.

%          x = y / 2;        Modulus – x is assign remainder of y/2;

--         x--;              Decrement – same as x = x – 1;

++         y++;              Increment – same as y = y + 1;
                                                                          32
        Some JavaScript Assignments
 Oper        Example             Result
 =           X = 1 + 2;          X is assign 3;

 +=          y += 2;             y= y + 2;

 -=          z -= 1              z = z – 1;

 *=          X *= 2;             x = x * 2;


 /=          x /= 2;             x = x / 2;


<HTML><HEAD><TITLE>Document Object</TITLE>
</HEAD>
<BODY bgColor=#ccccff>
<CENTER>
<H2>Using Variables </H2>
<SCRIPT language=JavaScript>
         x = 1;
         x++;
         x *= 2;
           document.write( "x=" + x + "<br>");
     </SCRIPT>                                    33
</CENTER></BODY></HTML>
                               Using prompt . . .
   Prompt will ask the user for input and set a
    variable with result. . .
    <HTML><HEAD><TITLE>Document Object</TITLE>
    </HEAD>
    <BODY bgColor=#ccccff>
    <CENTER>
    <H2>Using Variables </H2>
    <SCRIPT language=JavaScript>
             var rad = prompt('What is radius of wheel (in inches)?');
                 rad = parseInt(rad);
             var rotations = prompt('How many rotations did the wheel make?');
                 rotations = parseInt(rotations);                                   Convert character 10 to number 10
             var dist = 3.14 * (rad * rad) * rotations;
             var dist_feet = dist / 12;

                document.write( "Caluating distance using a wheel of radius " + rad + " inches");
            document.write( " that made " + rotations + " rotations <br>");
                document.write( "distance=" + dist + " inches<br>");
            document.write( "dist in feet=" + dist_feet + " feet<br>");
         </SCRIPT>
    </CENTER></BODY></HTML>




                                                                                                        34
         JavaScript Is also Event Driven
   In JavaScript you can specify actions to take on many different events:
     »   onAbort,
     »   onBlur,                User‟s cursor left a window item (then can specify some action)
     »   onChange,
     »   onClick,
     »   onDblClick,
     »   onDragDrop,
     »   onError,                   User clicks a window item (then can specify some action)
     »   onFocus,
     »   onKeyDown,
     »   onKeyPress,
     »   onKeyUp,
     »   onload,                   User puts cursor over a window item (then take some action)
     »   onMouseDown,
     »   onMouseOut,
     »   onMouseOver,
     »   onMouseUp,
     »   onMove,
     »   onReset,
                                   User selects a window item contents can specify some action
     »   onResize,
     »   onSelect,
     »   onSubmit,
                                                                                  35
     »   onUnload
       Example of a JavaScript Event
<html><head> <title>    my form </title> </head> <body>
<script>
 function genAlert()    {
     alert( "Don't do   that!" );           When click form item then
 }                                          do genalert() code.
 </script>
<form name="totals">
   <input type="text"   name="total" OnClick="genAlert()"></formm>
</body> </html>




                                                                        36
        Common
        Problem
         Area!
    People seem to forget this   Debugging JavaScript
      Both Netscatpe and Firefox have built in JavaScript
       debug tool
      From URL line type javascript:




                                                   Entering javascript: will open
                                                   a JavaScript debug window

                                              Any error messages, while script
                                              runs will show errors here

                                                                       37
                          Objectives
   Introduction to JavaScript
    » JavaScript: Its Beginnings
         – Advantages and disadvantages
         – How differs from html and server side programs
    »   Working with JS and HTML tags.
    »   Running onload, when done, on an event
    »   Using JS objects
    »   Objects with properties and methods
    »   Using conditional tests




                                                            38
                Competency
                  Alert:
                    You need to
                     know this   !
                                                       Conditionals
      JavaScript has many programming constructs
                              if ( x == 6 ) {
                                    document.write( “6 X=“ );                 1 or more statements to
                                    document.write( x );                      run when x is equal to 6.
                                    x += 1;
                              } else if ( x > 6 ) {                                  Test these only when x X is not 6
                                   document.write( “LT 6 X=“ );
                                        document.write( x );                          Run when X > 6.
                                        x += 1;
                              } else {
                                             document.write( “else 6 X=“ );               Run X is not 6 or gt 6
                                             document.write( x );
                              }
                              document.write( “x=“ + x );


HTML><HEAD><TITLE>Document Object</TITLE>
</HEAD>
<BODY bgColor=#ccccff>
<SCRIPT language=JavaScript>
x=5;
if ( x == 6 ) {
   document.write( "6 X=" );
   document.write( x );
   x += 1;
} else if ( x > 6 ) {
                      document.write( "LT 6 X=" );
       document.write( x );
     x += 1;
} else {
                      document.write( "else 6 X=" );
                      document.write( x );
}
document.wirte( "x=" + x );
</script>                                                                                                  39
<H2>Using Variables </H2>
</SCRIPT> </CENTER></BODY></HTML>
                 Example Grade Calculator
<HTML><HEAD><TITLE>Document Object</TITLE>
</HEAD>
<BODY bgColor=#ccccff>
<SCRIPT language=JavaScript>
var t1 = prompt( "Enter the score for the first test");
t1=parseInt(t1);
if ( t1 < 0 || t1 > 100 ) {
            alert( "Impossible score - I cannot go on!");
            exit;
}
var t2 = prompt( "Enter the score for the second test");
t2=parseInt(t2);
if ( t2 < 0 || t2 > 100 ) {
            alert( "Impossible score for t2 - I cannot go on!");
            exit;                                                   Notice how convert to
}
var t3 = parseInt(prompt( "Enter the score for the third test"));   number on 1 line
if ( t3 < 0 || t3 > 100 ) {
            alert( "Impossible score - I cannot go on!");
            exit;
}
var aver = ( t1 + t2 + t3 ) / 3;
var grade;
if ( aver >= 90 ) {
            grade = 'A';
} else if ( aver >= 80 ) {
            grade = 'B'
} else if ( aver >= 70 ) {
            grade = 'C'
} else {
            grade = 'D or lower';
}
document.write( 'Student average was ' + aver );
document.write( '<br>This score is a ' + grade );
</SCRIPT> </CENTER></BODY></HTML>
                                                                                     40
       JavaScript Conditional Tests
Oper    Example                  Result
==      if ( x == 1 )            Is true if x is equal to 1

!=      if ( apple != „blue‟ )   Is true if apple is NOT equal to „blue‟


>       if ( z > y )             Is true if z is greater that y

>=      if ( z >= y )            Is true if z is greater than or equal to y


<       if ( z < 3 )             Is true if z is less than 3


<=      if ( z <= y )            Is true if z is less than or equal to y


 &&     If ( a && b)             Is true if both a and b are true

||      If ( a || b)             Is true if both a || b are true

!       If ( !x )                Is true is x is false                        41
             Testing Browser Versions
<HTML><HEAD><TITLE>Document Object</TITLE></HEAD><BODY>
<SCRIPT language=JavaScript>
if ( navigator.appName == 'Netscape' ) {                   When netscape do this
  document.bgColor='#c6c6c6';
  document.write( 'name=' + navigator.appName );
  document.write( '<br>version=' + navigator.appVersion );
  document.write( '<br> appCodename=' + navigator.appCodeName );
  document.write( '<br> userAgenet=' + navigator.userAgent );
} else {                                                      When not netscape do this
  document.bgColor='yellow';
  document.write( 'Not netscape name=' + navigator.appName );
  document.write( '<br>version=' + navigator.appVersion);
  document.write( '<br> appCodename=' + navigator.appCodeName );
  document.write( '<br> userAgenet=' + navigator.userAgent );
}
</SCRIPT></BODY></HTML>




                                                                            42
                            Summary
   Introduction to JavaScript
    » JavaScript: Its Beginnings
         – Advantages and disadvantages
         – How differs from html and server side programs
    »   Working with JS and HTML tags.
    »   Running onload, when done, on an event
    »   Using JS objects
    »   Objects with properties and methods
    »   Using conditional tests




                                                            43
             Hands on assignment
   Write a simple javascript-based web
    page that
    » Redirects the browser to
      http://netscape.com if the user is using
      netscape or firefox
    » Redirects the browser to
      http://microsoft.com otherwise
    » Hint: you can redirect a browser by setting
      the window.location property.



                                                    44
One Possible Solution . . .
<HTML><HEAD><TITLE>Document Object</TITLE>
</HEAD>
<BODY>
<SCRIPT language=JavaScript>

if ( navigator.appName == 'Netscape') {
   window.location = 'http://www.netscape.com';
} else {

    window.location = 'http://www.microsoft.com';

}

</SCRIPT>
</CENTER></BODY></HTML>




                                                    45
      Another Hands on assignment
   Create a webpage with JavaScript that:
    » Displays the current date
    » Prompts the user for number of rows, cols
      and ticket cost.
    » Displays number of seats and total
      revenue.




                                                  46
      One Possible Solution

<HTML><HEAD><TITLE>Document Object</TITLE>
</HEAD>
<BODY>
<SCRIPT language=JavaScript>

document.write ("Today is " + new Date().toLocaleString()
+ "<br>");
var rows = parseInt( prompt("How many rows?"));
var cols = parseInt( prompt("How many seats per row?"));
var ticket = parseInt( prompt("How much per ticket?"));

var size = rows * cols;
var rev = size * ticket;
document.write( "We have " + size + " total seats.<br>" );
document.write( "We have maximum of " + rev + " total
revenue.<br>" );


</SCRIPT>
</CENTER></BODY></HTML>
                                                        47

								
To top