programming in javascript

Upload: cyberdairy

Post on 03-Jun-2018

238 views

Category:

Documents


1 download

TRANSCRIPT

  • 8/12/2019 Programming in JavaScript

    1/62

    XP

    1

    JavaScript

    Creating a Programmable Web Page

  • 8/12/2019 Programming in JavaScript

    2/62

    XP

    2

    Tutorial Objectives

    Understand basic JavaScript syntaxCreate an embedded and external scriptWork with variables and dataWork with data objects and extract valuesfrom datesWork with expressions and operators

    Create and call a JavaScript functionWork with arrays and conditional statementsLearn about program loops

  • 8/12/2019 Programming in JavaScript

    3/62

    XP

    3

    Server-Side Scripting

    a user must be connected to the Webserver to run the server-side scriptonly the programmer can create or alterthe scriptthe system administrator has to beconcerned about users continuallyaccessing the server and potentiallyoverloading the system

  • 8/12/2019 Programming in JavaScript

    4/62

    XP

    4

    Client-Side Scripting

    solve many of the problems associated withserver-side scripts

    can be tested locally without first uploadingit to a Web server

    are likely to be more responsive to the user

    can never completely replace server-sidescripts

  • 8/12/2019 Programming in JavaScript

    5/62

    XP

    5

    Introduction to JavaScriptJavaScript is an interpreted script languagefrom Netscape.JavaScript is used in Web site development to

    such things as:automatically change a formatted date on aWeb pagecause a linked-to-page to appear in a popup

    windowcause text or a graphic image to changeduring a mouse rollover

  • 8/12/2019 Programming in JavaScript

    6/62

    XP

    6

    Java vs. JavaScriptRequires the JDK tocreate the appletRequires a Java virtualmachine to run the applet

    Applet files are distinctfrom the XHTML codeSource code is hiddenfrom the userPrograms must be savedas separate files andcompiled before they canbe runPrograms run on theserver side

    Requires a text editorRequired a browser thatcan interpret JavaScriptcodeJavaScript can be placedwithin HTML and XHTMLSource code is madeaccessible to the userPrograms cannot writecontent to the hard diskPrograms run on theclient side

  • 8/12/2019 Programming in JavaScript

    7/62

    XP

    7

    Other Client-side Languages

    Internet Explorer supports JScript.

    JScript is identical to JavaScript, but thereare some JavaScript commands notsupported in JScript, and vice versa.

    Other client-side programming languagesare also available to Web page designers,

    such as the Internet Explorer scriptinglanguage, VBScript.

  • 8/12/2019 Programming in JavaScript

    8/62

    XP

    8

    Example of Web Site usingJavaScript

  • 8/12/2019 Programming in JavaScript

    9/62

    XP

    9

    Writing a JavaScript Program

    The Web browser runs a JavaScript programwhen the Web page is first loaded, or inresponse to an event.

    JavaScript programs can either be placeddirectly into the HTML file or they can besaved in external files.

    placing a program in an external file allowsyou to hide the program code from the usersource code placed directly in the HTML filecan be viewed by anyone

  • 8/12/2019 Programming in JavaScript

    10/62

    XP

    10

    Writing a JavaScript Program

    A JavaScript program can be placed anywherewithin the HTML file.Many programmers favor placing their

    programs between tags in order toseparate the programming code from the Webpage content and layout.Some programmers prefer placing programs

    within the body of the Web page at thelocation where the program output isgenerated and displayed.

  • 8/12/2019 Programming in JavaScript

    11/62

    XP

    11

    Using the Tag

    To embed a client-side script in a Webpage, use the element:

    script commands and comments

    To access an external script, use:

  • 8/12/2019 Programming in JavaScript

    12/62

    XP

    12

    CommentsThe syntax for a single-line comment is:// comment text

    The syntax of a multi-line comment is:/*

    comment text covering several lines*/

  • 8/12/2019 Programming in JavaScript

    13/62

    XP

    13

    Hiding Script from Older Browsers

    You can hide the script from these browsersusing comment tags:

    When a Web browser that doesnt supportscripts encounters this code, it ignores the tag.

  • 8/12/2019 Programming in JavaScript

    14/62

    XP

    14

    Writing Output to a Web Page

    JavaScript provides two methods to write textto a Web page:

    document.write(text);

    document.writeln(text); The document.writeln() method differs fromdocument.write() in that it attaches a carriagereturn to the end of each text string sent to the

    Web page.

    document.write("News Flash!
    ");

  • 8/12/2019 Programming in JavaScript

    15/62

  • 8/12/2019 Programming in JavaScript

    16/62

    XP

    16

    Working with Variables & Data

    A variable is a named element in a programthat stores information. The followingrestrictions apply to variable names:

    the first character must be either a letter oran underscore character ( _ )the remaining characters can be letters,numbers, or underscore characters

    variable names cannot contain spacesVariable names are case-sensitive.document.write(Year);

  • 8/12/2019 Programming in JavaScript

    17/62

    XP

    17

    Types of Variables

    JavaScript supports four different types ofvariables:

    numeric variables can be a number, such as

    13, 22.5, or -3.14159string variables is any group of characters,such as Hello or Happy Holidays! Boolean variables are variables that accept one

    of two values, either true or falsenull variables is a variable that has no value atall

  • 8/12/2019 Programming in JavaScript

    18/62

    XP

    18

    Declaring a Variable

    Before you can use a variable in yourprogram, you need to declare a variableusing the var command or by assigning the

    variable a value.Any of the following commands is alegitimate way of creating a variable named

    Month:

    var Month;var Month = December; Month = December;

  • 8/12/2019 Programming in JavaScript

    19/62

    XP

    19

    Working with Expressionsand Operators

    Expressions are JavaScript commands thatassign values to variables.

    Expressions are created using variables,values, and operators.

    The + operator performs the action ofadding or combining two elements. For

    example,var ThisMonth = Today.getMonth()+1;

  • 8/12/2019 Programming in JavaScript

    20/62

    XP

    20

    Operators

    Unary operators work on only onevariable.Binary operators work on two elementsin an expression.Ternary operators work on threestatement in an expression.

  • 8/12/2019 Programming in JavaScript

    21/62

    XP

    Operators in JavaScript

    ArithmeticRelational / Comparison

    LogicalIncrement / DecrementAssignment

    ConditionalConcatenation

  • 8/12/2019 Programming in JavaScript

    22/62

    XP

    Arithmetic Operators

    + (Addition)- (Subtraction)

    * (Multiplication) / (Division)% (Modulus)

  • 8/12/2019 Programming in JavaScript

    23/62

    XP

    Relational / Comparison

    === (Equal to)

    != (Not equal to)

  • 8/12/2019 Programming in JavaScript

    24/62

    XP

    Logical Operator

    && (AND)|| (OR)

    ! (NOT)

  • 8/12/2019 Programming in JavaScript

    25/62

    XP

    Increment / Decrement Op.

    ++--

  • 8/12/2019 Programming in JavaScript

    26/62

    XP

    26

    Assignment Operators

    Expressions assign values using assignmentoperators. = is the most common one. Additional includes the += operator

    The following create the same results:x = x + y;x += yEither of the following increase the value ofthe x variable by 2:x = x + 2;x += 2

  • 8/12/2019 Programming in JavaScript

    27/62

    XP

    Assignment Operator

    =+=

    -=*=

    /=

    %=

  • 8/12/2019 Programming in JavaScript

    28/62

    XP

    28

    A Conditional Operator

    tests whether a specific condition is true andreturns one value if the condition is true and adifferent value if the condition is false.

    Message = (mail == Yes) ? You havemail: No mail; tests whether the mail variable is equal to thevalue Yes

    if it is, the Message variable has the value You have mail ; otherwise, the Message variable has thevalue No mail .

  • 8/12/2019 Programming in JavaScript

    29/62

    XP

    Concatenation operator

    + is used to concatenate two string.

    var num = 10;document.write(Value of number is + num);

  • 8/12/2019 Programming in JavaScript

    30/62

    XP

    Control Flow Statements

    SequentialConditional/Branching

    If else statementSwitch statement

    Iterative/LoopingForWhileDo while

  • 8/12/2019 Programming in JavaScript

    31/62

    XP

    31

    If statementif ( condition ) {

    JavaScript Commands}

    condition is an expression that is either trueor falseif the condition is true, the JavaScriptCommands in the command block are

    executedif the condition is not true, then no action istaken

  • 8/12/2019 Programming in JavaScript

    32/62

    XP

    32

    Using an If...Else Statement

    if ( condition ) { JavaScript Commands if true

    } else

    JavaScript Commands if false}

    condition is an expression that is either trueor false, and one set of commands is run ifthe expression is true, and another is run ifthe expression is false

  • 8/12/2019 Programming in JavaScript

    33/62

    XP

    Switch statementThe switch statement is used to perform differentaction based on different conditions.switch(expr){case 1:

    execute code block 1 break;

    case 2:execute code block 2 break;

    default:code to be executed if expr is different from

    case 1 and 2}

  • 8/12/2019 Programming in JavaScript

    34/62

    XP

    34

    Iterative/Looping

    A program loop is a set of instructionsthat is executed repeatedly.There are two types of loops:

    loops that repeat a set number oftimes before quittingloops that repeat as long as a certaincondition is met

  • 8/12/2019 Programming in JavaScript

    35/62

    XP

    35

    The For Loop

    The For loop allows you to create a group ofcommands to be executed a set number oftimes through the use of a counter that tracks

    the number of times the command block hasbeen run.Set an initial value for the counter, and eachtime the command block is executed, the

    counter changes in value.When the counter reaches a value above orbelow a certain stopping value, the loop ends.

  • 8/12/2019 Programming in JavaScript

    36/62

    XP

    36

    The For Loop Continued

    for ( start ; condition ; update ) { JavaScript Commands

    }

    start is the starting value of the counter condition is a Boolean expression that must

    be true for the loop to continue update specifies how the counter changes in

    value each time the command block isexecuted

  • 8/12/2019 Programming in JavaScript

    37/62

    XP

    37

    The While Loop

    The While loop runs a command group aslong as a specific condition is met, but it doesnot employ any counters.

    The general syntax of the While loop is:while ( condition ) { JavaScript Commands

    } condition is a Boolean expression that can

    be either true or false

  • 8/12/2019 Programming in JavaScript

    38/62

    XP

    The do while loop

    In this loop will execute the codeblock once, before checking if thecondition is true, then it will repeatthe loop as long as the condition istrue.

  • 8/12/2019 Programming in JavaScript

    39/62

    XP

    Syntax of do while loop

    do{code block to be executed}

    while ( condition );

  • 8/12/2019 Programming in JavaScript

    40/62

    XP

    40

    Using Arrays

    An array is an ordered collection of valuesreferenced by a single variable name.The syntax for creating an array variable is:

    var variable = new Array( size ); variable is the name of the array variablesize is the number of elements in the array(optional)

    To populate the array with values, use:variable [ i]= value ; where i is the i th item of the array. The 1 st itemhas an index value of 0 .

  • 8/12/2019 Programming in JavaScript

    41/62

    XP

    41

    Using Arrays

    To create and populate the array in a singlestatement, use:var variable = new Array( values );

    values are the array elements enclosed inquotes and separated by commasvar MonthTxt =new Array(, January , February , March , April , May , June ,

    July , August , September , October , November , December ); January will have an index value of 1.

  • 8/12/2019 Programming in JavaScript

    42/62

    XP

    42

    Creating JavaScript Functions

    function function_name ( parameters ) {

    JavaScript commands

    }

    parameters are the values sent to thefunction (note: not all functions requireparameters)

    { and } are used to mark the beginning andend of the commands in the function.

  • 8/12/2019 Programming in JavaScript

    43/62

    XP

    43

    Creating JavaScript Functions

    Function names are case-sensitive.The function name must begin with a letter orunderscore ( _ ) and cannot contain any

    spaces.There is no limit to the number of functionparameters that a function may contain.The parameters must be placed within

    parentheses, following the function name, andthe parameters must be separated bycommas.

  • 8/12/2019 Programming in JavaScript

    44/62

    XP

    44

    Performing an Action with aFunction

    The following function displays a message withthe current date:

    function ShowDate ( date ) {

    document.write(Today is + date +
    );

    }

    there is one line in the functions command

    block, which displays the current date alongwith a text string

  • 8/12/2019 Programming in JavaScript

    45/62

    XP

    45

    Performing an Action with aFunction

    To call the ShowDate function, enter:

    var Today = 3/9/2006;

    ShowDate(Today);

    the first command creates a variable named Today and assigns it the text string, 3/9/2006 the second command runs the ShowDatefunction, using the value of the Today variableas a parameterresult is Today is 3/9/2006

  • 8/12/2019 Programming in JavaScript

    46/62

    XP

    46

    Returning a Value from aFunction

    To use a function to calculate a value use thereturn command along with a variable or value.function Area ( Width, Length ) {

    var Size = Width*Length;return Size;

    }the Area function calculates the area of a

    rectangular region and places the value in avariable named Size the value of the Size variable is returned bythe function

  • 8/12/2019 Programming in JavaScript

    47/62

    XP

    47

    Placing a Functionin an HTML File

    The function definition must be placedbefore the command that calls the function.One convention is to place all of the

    function definitions in the section.A function is executed only when called byanother JavaScript command.

    Its common practice for JavaScriptprogrammers to create libraries of functionslocated in external files.

  • 8/12/2019 Programming in JavaScript

    48/62

    XP

    Example of Function

    function showmessage() {alert("WebCheatSheet - JavaScript Tutorial!");

    }

  • 8/12/2019 Programming in JavaScript

    49/62

    XP

    JavaScript Events

    Events are normally used incombination with functions, and thefunction will not be executed beforethe event occurs (such as when auser clicks a button).

  • 8/12/2019 Programming in JavaScript

    50/62

    XP

    Mouse Events

  • 8/12/2019 Programming in JavaScript

    51/62

  • 8/12/2019 Programming in JavaScript

    52/62

    XP

    Form Events

  • 8/12/2019 Programming in JavaScript

    53/62

    XP

    Objects in JavaScript

    JavaScript is an Object OrientedScripting language because itprovides us following features

    EncapsulationInheritancePolymerphism

  • 8/12/2019 Programming in JavaScript

    54/62

    XP

    Object in JavaScript

    Object contains two elementsProperties or DataMethods or Functions

    For example if STUDENT is an objectProperties (rollnumber, name, course)Methods (deposit fees, issue books)

    To access properties or methodsObject.method, object.property

  • 8/12/2019 Programming in JavaScript

    55/62

    XPUser-defined objects

    // Define a function which will work as a methodfunction addPrice(amount){

    this.price = amount;}

    function book(title, author){this.title = title;this.author = author;this.addPrice = addPrice; // Assign that method as property.

    }

  • 8/12/2019 Programming in JavaScript

    56/62

    XP

    var myBook = new book("Perl", "Mohtashim");myBook.addPrice(100);document.write("Book title is : " + myBook.title + "
    ");

    document.write("Book author is : " + myBook.author +"
    ");

    document.write("Book price is : " + myBook.price +"
    ");

  • 8/12/2019 Programming in JavaScript

    57/62

    XP

    JavaScript Native Objects

    Number ObjectBoolean Object

    String ObjectArray ObjectDate Object

    Math ObjectRegExp Object

  • 8/12/2019 Programming in JavaScript

    58/62

    XP

    Number ObjectMAX_VALUE The largest possible value a

    number in JavaScript can have1.7976931348623157E+308

    MIN_VALUE The smallest possible value anumber in JavaScript can have5E-324

  • 8/12/2019 Programming in JavaScript

    59/62

    XP

    Number Methods

    toFixed() Formats a number with a specificnumber of digits to the right of thedecimal.

    toPrecision() Defines how many total digits (including

    digits to the left and right of the decimal)to display of a number.

    http://www.tutorialspoint.com/javascript/number_tofixed.htmhttp://www.tutorialspoint.com/javascript/number_toprecision.htmhttp://www.tutorialspoint.com/javascript/number_toprecision.htmhttp://www.tutorialspoint.com/javascript/number_tofixed.htm
  • 8/12/2019 Programming in JavaScript

    60/62

    XP

    String Object

    The String object let's you work with aseries of characters and wrapsJavascript's string primitive data typewith a number of helper methods.

  • 8/12/2019 Programming in JavaScript

    61/62

  • 8/12/2019 Programming in JavaScript

    62/62

    XP

    String Methods