Docstoc

ECT 270 Introduction to JavaScript

Document Sample
ECT 270 Introduction to JavaScript Powered By Docstoc
					ECT 270 Client-side web application development



       Introduction to JavaScript
      What is Java Script?
   JavaScript is not an all-purpose
    programming language
     What is JavaScript?
     JavaScript is NOT Java
   JavaScript is an interpreted web scripting
    language run from the Web browser ( as
    opposed to CGI scripting that runs on the
    server side)
        JavaScript as DHTML
   JavaScript is part of a growing number of HTML
    extensions known as Dynamic HTML (DHTML).
    DHTML is comprised of
       CSS (cascading style sheets)
       DOM (document object module)
       Scripting (Javascript and VBscript)
   Together, these technologies make the Web
    what it is today, by enabling far more advanced
    interactivity and much flashier styling than would
    HTML on it‟s own
    Background of JavaScript
   Originally created by a team at Netscape and
    Sun as a subset of Java, with some differences:
       Doesn‟t need to be compiled, the browser has an
        interpreter that process the commands in a script
       JavaScript commands can be embedded directly into
        an HTML file (not in a separate applet)
       You don‟t need to know Object Oriented
        Programming to use it.
     Current version of JavaScript
   The European Computer Manufacturers
    Association (ECMA) is now in charge of
    the development of a JavaScript standard.
   The current version of JavaScript is called
    ECMA-262 and is supported by most
    browsers.
   Another client-side scripting language
    supported by Internet Explorer is VBScript
        Debugging JavaScript
   Syntactic errors: In IE
       Internet Options/Advanced
       Check box:”Display a notification about every script
        error”
       Check the line indicated and the ones above and
        below
       In Notepad: Edit/Goto enter the line number
   If you have syntactic errors the script will not
    run
     Debugging JavaScript
   Semantic errors:the syntax is correct
    but will produce the wrong result
   Calculate the average of two numbers
       Correct: z = (x+y)/2;
       Incorrect: a = x+y/2;
   If x=10 and y=30
       z=20
       a=25
       JavaScript and HTML
   You can place the JavaScript commands in a
    separate file
   Then link the HTML file to that file by using
    the <SCRIPT> tag in the head of the file

<SCRIPT SRC=URL LANGUAGE=“javascript”>
     other script commands and comments
</SCRIPT>

SCRIPT is the tag, LANGUAGE is the attribute, javascript is
the value
         JavaScript and HTML
You can place the JavaScript commands
directly in the HTML file
The <SCRIPT> tag can go in the <HEAD>

or the <BODY>
<SCRIPT LANGUAGE=“JavaScript”>
    <!- - Hide this script from browsers that don‟t support JavaScript
         script commands and comments
    // Stop hiding from other browsers - ->
</SCRIPT>
      Keep in mind …
   JavaScript is case sensitive (commands,
    objects, methods, function names etc ..)
   Each JavaScript command line must end
    with a semi-colon (;)
   One-line comment: // comment
   Multi-line comment: /* comment */
                                             07_JSOutput.htm


        Sending output to the Web page
    <pre>
   document.writeln(“string”);
     positions output cursor on next line when finished
    </pre>
   document.write(“string”);
       Leaves the output cursor where it is when done
        executing
 The string can contain any text or HTML
  source code
document is the object, write is the method
     JavaScript Variables
   A variable is a named element in a program,
    used to store and retrieve information
   Variable names are case sensitive, cannot
    contain spaces, and must start with a letter
    or an underscore
   When you have more than one word in a
    variable name, start with a lowercase first letter
    and capitalize the first letter of any subsequent
    word: currentDate
       Declaring a JavaScript variable
   var variableName;
    (indicates that variableName is a program
    variable, it doesn‟t occupy any space)
   var variableName = value;
   variableName = value
    (also assign an initial value to the variable)
   You do NOT need to declare the variable
    type
                                          07_JSVar.htm


      Different types of variables
   Numeric: 13, 22.3,-3.1415, 5.1E2 (5.1x102)
   String: any group of characters within quotation
    marks. “This is a string”, „another string‟, „3.14‟,
    “” (the empty string)
   Boolean: can only be true or false
    var isBad = true
   Null variable: is a variable that has no value
    (assigned yet)
    var noGivenValue
        The Date object
   JavaScript doesn‟t have a Date data type.
    You need to create a date object that
    contains date information.
dateVariable = new Date(“month, day, year, hours:minutes:seconds”);
                               or
dateVariable = new Date(year, month, day, hours,minutes,seconds);


 taxDay       = new Date (“April, 15,2002,24:0:0”);
              or = new Date (2002,3,15,);

    today     = new Date ();
       Dates in JavaScript
   Seconds and minutes: 0-59
   Hours:0-23
   Week Days:0 (Sunday) – 6 (Saturday)
   Day: 1-31 (day of the month)
   Months:0 (January) –11 (December)
   Year: since 1900
   Time: in millisecond since January 1, 1970
    taxDay   = new Date (2002,15,3,0,0,0);
    Date methods
For retrieving date and time value
        dateVariable.getFullYear();
        dateVariable.getMonth();
        dateVariable.getDate();
        dateVariable.getDay();
        dateVariable.getHours();
        dateVariable.getMinutes();
        dateVariable.getSeconds();

 taxDay    = new Date (2002,15,3,0,0,0);

taxDay.getMonth(); //returns 3
Date methods
Arithmetic operators




x=5+3;   „x equals 8
y=x++;   „y equals 9
z=-y     „y equals -9   07_JSMath.htm
JavaScript built-in object for math calculations
     Math.abs(numberVariable)
        Returns the absolute value of numberVariable

     Math.sin(numberVariable)
        Calculates the sine of numberVariable, where numberVariable

         is an angle epressed in radians
     Math.cos(numberVariable)
        Calculates the cosine of numberVariable, where

         numberVariable is an angle expressed in radians
     Math.round(numberVariable)
        Rounds the value of numberVariable to the closet integer

     Math.ceil(numberVariable)
        Rounds the value of numberVariable up to the next highest

         integer
     Math.floor(numberVariable)
        Rounds the value of numberVariable down to the next lowest

         integer
     Math.random()
        Returns a random number between 0 and 1
        Addition vs Concatenation
result = var1 + var2
 If both are number variables:
       Adds var1 to var2
       Assigns the result to the variable result
       result is a number variable
   If at least one of the two is a string:
       Concatenate var1 and var2
       Assigns the result to the variable result
       result is a string variable
Assignment operators




This operators are used with any data type to
assign a specific value to a variable
   x=5;      „x   equals   5
   x+=6;     „x   equals   11
   x-=2;     „x   equals   9
   x*=3;     „x   equals   27
   x/=9      „x   equals   3
        JavaScript functions
   A function is used to group related, script statements
    together in reusable units. A function might perform
    actions or calculates a value
   It consists of:
       A function name: it identifies the function and it is used to call
        the function when needed)
       A set of parameters: a list of variable names that will contain
        the values used by the function, grouped within ()
       A command block: a set of commands that are executed when
        the function is used. The commands are grouped within {}



function function_name (par1, par2, ..){JavaScript commands}
     Performing an action with a function

   Define the function in the <HEAD> and
    always before the command that calls
    the function
function showDate (date){document.write(“Today is “+date);}

Call (or run) the function when needed,
passing the parameters by value.
var ThisDay = “5/5/2002”;              Today is 5/5/2002
showDate(ThisDay);
                                              07_JSFct2.htm



     Returning a value from a function
   You can use a function to calculate a value
   You need a return command and a variable
    at the end of the function‟s command block
function average(num1, num2){
         var avrg = (num1+num2)/2;     Declaring the function
          return avrg;}

var x= 10;                             Function is called
var y=30;                              Parameters 10 and 30
var z= average(x,y);                   are passed
document.write(“the average is “+z);   z =result of function
                                         07_JSScope.htm



        Variable scope
   The scope of a variable is the range of
    statements over which it is visible.
      Local variables Any variable declared
       (var) within the body of a function, exists
       only within that function
      Global variables are variables declared
       outside the body of a function.They are
       available through the script.
   Any variable not explicitly declared using
    var is global
       The window object and methods
   The window object represents a browser window.
    Window methods are
   window.alert("string“); Shows an alert
    window with text string, and 'OK' button
   window.prompt(“string of character”, “default
    value”); Prompts user for input
   Window.confirm(“string”);If the OK button is
    clicked, the confirm method returns the value “true”
   window.close();
   window.open(URL, windowname);
                                                  07_JSStatusBar.htm


        Fun functions
   window.status status bar function changes the text
    displayed in the status bar (bottom left corner of the
    browser window)
    <a href=“http://www.cs.depaul.edu”
    onMouseover=“window.status=`CTI homepage`; return true”
    onMouseout=“window.status=“”>CTI</a>

   document.lastModified reflects when the page
    was last modified
    var modifiedDate=document.lastModified;
    document.write(modifiedDate);
Average                function average(num1, num2){
revisited                       var avrg = (num1+num2)/2;
                                 return avrg;}
firstNumber = window.prompt("Enter an integer","0");
secondNumber = window.prompt("Enter another","0");

x=parseInt (firstNumber);           Transform string input
y=parseInt (secondNumber);          into an integer

                                    Call function
var z= average(x,y);
                                    Return average
document.writeln(“First number “+x);
document.writeln(“Second number “+y);
document.writeln(“The average of x and y is “+z);

                          07_JSAverage.htm   07_JSMathFct.htm
       Objects and methods
   JavaScript is an object-based language: it is
    based on manipulating objects by modifying their
    properties or applying methods to them.
   Objects are items that exist in a defined space in a
    Web page (window, form etc)
   Each object has properties that describe its
    appearance, purpose, or behavior
   An object can have methods, which are actions
    that can be performed with or to it.
   “An object is a bag of properties and methods”
    Objects in JavaScript




Object: browser
Properties: type (Netscape, Internet Explorer), version (3.1)
Methods: open, close, reload the content
Object hierarchy




window.document.formName

document.formName
Objects and their methods
       Working with object properties
   Change the value of a property
    object.property = expression
    document.bgColor=“red”
   Save object property as a variable
    variable = object.property
    pageColor =document.bgColor
      JavaScript events
   An event is a specific action that triggers
    the browser to run a block of JavaScript
    commands
                                                       07_JSEventHand.htm



        JavaScript event handlers
    An event handler is code added to an HTML tag
     that is run whenever a particular event occurs
     within a tag
    Different HTML tags have different event handlers
<TAG event_handler =“JavaScript commands;”>

<FORM>
<INPUT TYPE=RADIO onClick=“document.bgColor=„red‟;”>red<BR>
<INPUT TYPE=RADIO onClick=“document.bgColor=„blue‟;”>blue<BR>
</FORM>

INPUT is the tag, onClick is the event, “document…” is the event handler
Event handlers
                                                             07_JSAlert
Greeting the visitor
<HTML><HEAD><TITLE>JavaScript Events</TITLE>
<SCRIPT LANGUAGE="JavaScript">
var visitor_name = ""
function greet_visitor() {
 visitor_name = prompt("Please enter your name", "Enter your name
    here");
    alert("Welcome " + visitor_name + "!");       }
function farewell_visitor() {
    alert("Thanks " + visitor_name + " for visiting this Web page!");}
</SCRIPT></HEAD>
<BODY onLoad="greet_visitor()" onUnload="farewell_visitor()”>
<FORM>
<INPUT TYPE="text" NAME="text_field" SIZE="25"
    onChange="alert('The value of the text_field has changed.')"><BR>
<INPUT TYPE="button" VALUE="Display Text Field Contents"
    onClick="alert(text_field.value)">
</FORM></BODY></HTML>

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:8
posted:8/1/2010
language:English
pages:40