Quick Introduction to JavaScript Module 2

download Quick Introduction to JavaScript Module 2

of 64

description

Quick Introduction to JavaScript Module 2

Transcript of Quick Introduction to JavaScript Module 2

  • Quick Overview of JavaScript Ali Chalhoub

    March, 2014 Internal

    Module 2

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 2 Internal

    Agenda

    Quick Overview of JavaScript

    Whats JavaScript

    How to use it

    Examples

    Debug JavaScript

    Advanced Topic

    Working with JavaScript Object and Arrays

    Demo JavaScript and HTML 5

    JavaScript best practice tips

    Summary

  • Quick Overview of JavaScript

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 4 Internal

    Whats JavaScript?

    JavaScript

    Is a Programming language that allow the user to interact with the user interface and perform actions without going back to the server.

    Runs in the client machine and not the back-end server.

    It is used for form validation before submitting the result to the back-end server for processing.

    It is NOT java.

    It is used with HTML web pages or embedded within an HTML page

    It can be stored on its own file and referenced by an html page

  • How to use JavaScript

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 6 Internal

    How to Use JavaScript?

    In order to use JavaScript programming, you need the following:

    A web server in production

    Apache

    IIS

    Text Editor

    Web browser

    It can run locally without a web server as well as a stand alone application

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 7 Internal

    Syntax Ex1

    1.

    2.

    3.

    4. Hello World

    5.

    6. document.write("Hello World!!!

    Using JavaScript");

    7.

    8.

    9.

    The

    tag

    It defines the block where the JavaScript reside and gets executed.

    JavaScript is case sensitive ( i.e document.write() works Document.write() will not be recognized

    To write something to the page and display to the user, you will use

    document.write();

    A tag must be closed when you are done. ( i.e )

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 8 Internal

    Syntax Ex1

    1.

    2.

    3.

    4. Hello World

    5.

    6. document.write("Hello World!!!

    Using JavaScript");

    7.

    8.

    9.

    JavaScript code can be embedded

    In the body tag of the web page

    It can be embedded in the header tag

    To display a literal string, you use the double quotation symbol

    Within a string in JavaScript, you can embed an THML tag ( i.e document.write( hello World);

  • Examples Alter HTML Element

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 10 Internal

    Syntax Ex 2 Altering an HTML Element

    1.

    2.

    3.

    4. Altering HTML element

    5. This is a

    paragraph that is going to be

    altered by JavaScript.

    6.

    7. document.getElementById("myParaID")

    .innerHTML="This is the new

    paragraph";

    8.

    9.

    10.

    Altering an HTML element

    1. If an HTML tag must have an ID in order

    to be altered. ( i.e )

    2. In JavaScript code block, you will use the

    getElementByID function of the

    document object. ( i.e document.getElementById("myPar

    aID")

    3. Then you will use the innerHTML

    property to change the text value. ( i.e: document.getElementById("myParaID").innerHTML

    ="This is the new paragraph";

  • Examples Referencing a JavaScript External File

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 12 Internal

    Syntax Ex3 of Referencing an External JavaScript File

    1.

    2.

    3.

    4. Altering HTML element

    5. My First

    Paragraph.

    6.

    7.

    8.

    Referencing external JavaScript file

    1.

    Within the tag use the src attribute to reference your JavaScript file.

    Make sure if this is a file on the web, use the full URL address

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 13 Internal

    Content of the External JavaScript File

    1. document.getElementById("myParaID").

    innerHTML="This is the new paragraph

    from external file";

    When referencing an external JavaScript

    file,

    1. No need to use the tag within the

    file.

    2. You can start writing javascript code right

    away. As you can see on the left, we

    wrote the javascript

    document.getElementById directly in the

    external file.

  • Examples Calling a Function

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 15 Internal

    Syntax Ex4 Calling a JavaScript Function

    1.

    2.

    3.

    4. My Web Page

    5. This a paragraph within the para.

    tag.

    6. This a div within the div block

    7.

    8. Click

    Me

    9.

    10.

    11.function changeDiv()

    12.{

    13.document.getElementById("myParID").innerHTML="Hello

    Paragraph";

    14.document.getElementById("myDivID").innerHTML="Hello

    div";

    15.}

    16.

    17.

    18.

    Calling a JavaScript Function

    1. Create a function within the tag. (

    i.e: function changeDiv(){ }

    2. Define a block of code within the curly

    bracket. This code can only be executed

    when the function is called.

    3. In this example on the left side, we have

    Two HTML tags, one is a , and second is a

    We have a button that when we click it, it will alter the content of these tags

  • Examples Comments

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 17 Internal

    Comments in JavaScript

    1.

    2.

    3.

    4. Altering HTML element

    5. This is a paragraph

    that is going to be altered by

    JavaScript.

    6.

    7. //This is a comment about innerHTML

    8. document.getElementById("myParaID").i

    nnerHTML="This is the new paragraph";

    9.

    10.

    11.

    A comment basically

    1. It allow the user to put a note or some

    detail explaination about certain code.

    2. A comment gets ignored during runtime

    and does not get executed.

    3. To make a single line comment in

    javascript, use double slash ( i.e // )

    //This is a comment

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 18 Internal

    Comments in JavaScript

    1.

    2.

    3.

    4. Altering HTML element

    5. This is a paragraph that is

    going to be altered by JavaScript.

    6.

    7. /* This is a comment about innerHTML.

    It allows the developer to change

    the content of a html tag dynamically

    8. */

    9. document.getElementById("myParaID").innerHTML="

    This is the new paragraph";

    10.

    11.

    12.

    Multiple line comments

    1. If an explanation is required which takes

    more than one line, then use the following

    syntax /* */

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 19 Internal

    Comments in JavaScript

    1.

    2.

    3.

    4. My Web Page

    5. This a paragraph within the para.

    tag.

    6. This a div within the div block

    7.

    8. Click

    Me

    9.

    10.

    11.function myFunction()

    12.{/*

    13.document.getElementById("myParID").innerHTML="Hello

    Paragraph";

    14.document.getElementById("myDivID").innerHTML="Hello

    div";

    15.*/

    16.}

    17.

    18.

    19.

    To prevent a code or statement from

    execution, just comment the statement

    1. Example: // document.write(not good one)

    To prevent multiple line of codes or

    statements from execution, you can use /*

    */ block as well.

  • Examples Variables

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 21 Internal

    Syntax Ex5 Variables in JavaScript

    1.

    2.

    3.

    4.

    5. var myvar;

    6. myvar="Initialize my Variale with text";

    7. document.write(myvar);

    8. document.write("");

    9. myvar="This is my value now";

    10. document.write(myvar);

    11.

    12.

    13.

    Variables are used to set reference to an

    object or to store value in it and use it

    later

    1. Example: var myvar;

  • Examples if statement

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 23 Internal

    Syntax Ex6 If Statement block in JavaScript

    1.

    2.

    3.

    4. Greeting

    5.

    6.

    7. function myFunction()

    8. {

    9. var sGreeting="";

    10. var myTime=new Date().getHours();

    11. if (myTime

  • Examples Alert Statement

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 25 Internal

    Alert Statement in JavaScript

    1.

    2.

    3.

    4. Greeting

    5.

    6.

    7. function myFunction()

    8. {

    9. var sGreeting="";

    10. var myTime=new Date().getHours();

    11. alert("before reaching if statement");

    12. if (myTime

  • Examples String Concatenation

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 27 Internal

    Syntax Ex7 String Concatenation

    1.

    2.

    3.

    4.

    5. var myvar;

    6. myvar="This is a very long text that I know it will" +

    7. " not fit on one line; therefore; I need to use the" +

    8. " concatenation symbol in JavaScrpit.";

    9. document.write(myvar);

    10. document.write("");

    11.

    12.

    13.

    myvar variable now contains a very large

    text that cannot fit on one line. Therefore,

    we have to break the string. To do that:

    1. Put the string in double quotation or

    single quote.

    2. When you decide to break the line and

    continue in the next line, close the text

    string with a double quotation or single

    quotation. Which ever you started with,

    you will close with it.

    3. Once you reach the end of the text, just

    close the string with a quotation or double

    quotation and add semi-colon.

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 28 Internal

    Mixing Double Quotation and Single Quotation

    1.

    2.

    3.

    4.

    5. var myvar;

    6. myvar= 'This is a very long text that I know it will' +

    7. ' not fit on one line; therefore; I need to use the' +

    8. ' concatenation symbol in JavaScrpit. This is called' +

    '"JavaScript Programming!!!"';

    9. document.write(myvar);

    10. document.write("");

    11.

    12.

    13.

    myvar variable needs to contain the

    following string "JavaScript

    Programming!!!". To do that:

    1. Because you want double quotation

    within the string, then the outer string will

    use single quotation.

    2. Follow the rest of the syntax to combine

    the lines from the previous slide.

  • Debug JavaScript

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 30 Internal

    Debug JavaScript

    To debug a JavaScript page, we need the following web browser:

    Chrome

    Chrome debug allows you to :

    Set a breakpoint in a particular statement

    F8: Resume

    F10: Use F10 function to step over a statement.

    F11: Use F11 to step into a statement.

    You can use watch to inspect a variable

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 31 Internal

    Activate the Debugger

    To activate the Chrome debugger:

    1. In Chrome open the website, URL, or the file you are interested in debugging

    2. Press F12 function key

    3. You should see something like that:

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 32 Internal

    Activate the Debugger

    Settings and

    Configuration

    Source

    Code to

    Debug

    Ste

    ps

    Play Icon Resume

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 33 Internal

    Activate the Debugger

    To set a breakpoint on particular line, do the following:

    1. In Chrome open the website, URL, or the file you are interested in debugging

    2. Press F12 function key to open

    the debugger

    3. Click on Sources option

    4. Click on the tiny play icon under

    sources to show the navigation

    5. Now select your file and click on it

    6. Click on the line number using your

    mouse to set the break point

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 34 Internal

    Activate the Debugger

    1

    2

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 35 Internal

    Activate the Debugger

    3

    Double click on

    the file

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 36 Internal

    Activate the Debugger

    4

    No content,

    needs to reload

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 37 Internal

    Activate the Debugger

    5

    Reloading the page

    to step into the

    code After

    Reloading

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 38 Internal

    Activate the Debugger

    6

    Click on the line you want to

    debug and reload the page to

    break into it

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 39 Internal

    Activate the Debugger

    Now you are stepping into your

    code

    7

    Click on step

    over icon or

    press F10

    10

  • Advanced - JavaScript Objects &

    Array

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 41 Internal

    Whats JavaScript Object?

    JavaScript Object

    Is a set of properties and functions that describe the characteristics of something ( object), ( i.e a car, tree, BCP incident).

    Is a type of object-oriented programming language.

    Is a prototype-based and does not support the class statements.

    A vehicle is an object in JS. However, car, truck are prototypes of the object vehicle.

    Note: Anything in JavaScript is consider it an object. ( i.e Dates, Strings, etc)

    Ex: var txtObj = new String("Welcome to JavaScript") ;

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 42 Internal

    Vehicle Object

    Object Properties Methods

    company="company Name"

    model = "vehicle model"

    color= "vehicle color"

    weight="vehicle weight"

    start()

    stop()

    drive()

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 43 Internal

    Incident Object Example

    Object Properties Methods

    status="customer action"

    processor ="Ali Chalhoub"

    priority="Very High"

    customer="SAP IT"

    rampup=true

    irt="OK"

    mpt="3%"

    component="MOB-ONP-COR"

    incidentnumber="2113/2014"

    pickup()

    dispatch()

    setStatus()

    assignProcessor()

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 44 Internal

    Syntax Creating an Object in JavaScript

    There are two methods to create a JavaScript object.

    1. First method is to create a direct instance of the Object and add properties to it.

    2. Or create your own custom class with your own Constructor.

    Something to be aware of:

    Class Defines the characteristics of the Object Object An Instance of a Class. Property An Object characteristic, such as model, firstname, lastname, age, color. Method An Object capability, such as walk. Constructor A method called at the moment of instantiation where you can initialize your

    variables or properties of an object instance.

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 45 Internal

    Syntax Creating Object using a Direct Instance Method

    To define a direct instance of an Object, you do the following:

    This code shows how you can instantiate an instance of an Object.

    This code below shows you how to add a property to your object instance

    Accessing the object instance method

    var incidentObj = new Object();

    incidentObj.priority = "High";

    incidentObj.getIncidentNumber();

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 46 Internal

    Syntax Creating Object using a Direct Instance Method

    To define a direct instance of an Object, you do the following:

    This code shows how you add a function to an instance of an Object.

    incidentObj.getIncidentNumber= function() {

    return this.incidentnumber;

    }

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 47 Internal

    Ex7 Creating Object using a Direct Instance Method

    1.

    2.

    3.

    4.

    5. var incidentObj=new Object();

    6. incidentObj.incidentnumber="2134/2014";

    7. incidentObj.irt="OK";

    8. incidentObj.processor="i826599";

    9. incidentObj.customer="SAP IT";

    10.incidentObj.component="MOB-ONP-COR";

    11.incidentObj.getIncidentInfo = function(){

    12. return ("Incident: #" + incidentObj.incidentnumber + "" + "Support Name: " +

    incidentObj.processor + "" + "Customer:" + incidentObj.customer);

    13.}

    14.document.write( incidentObj.getIncidentInfo() );

    15.

    16.

    17.

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 48 Internal

    Alternative Syntax Creating Object using a Direct Instance Method

    There is an alternative way to create an object. It is called object literals

    This code shows how you can instantiate an instance of an Object.

    incidentObj = {incidentnumber:"2134/2014",irt:"OK",processor:"i826599"};

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 49 Internal

    Syntax Creating Object with Constructor

    To define an object that uses a constructor, do the following:

    function incident(inum,prty,processor,cust, comp){

    this.incidentnumber=inum;

    this.priority=prty;

    this.processor = processor;

    this.customer=cust;

    this.component=comp;

    this.getIncidentInfo=getIncidentInfo;

    function getIncidentInfo()

    {

    return ("Incident: #" + this.incidentnumber + "" + "Priority: " +

    this.priority + "Support Name: " + this.processor + "" +

    "Customer:" + this.customer);

    }

    }

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 50 Internal

    Syntax Ex 8 Creating Object using a Object Constructor

    1.

    2.

    3.

    4.

    5. function incident(inum,prty,processor,cust, comp){

    6. this.incidentnumber=inum;

    7. this.priority=prty;

    8. this.processor = processor;

    9. this.customer=cust;

    10. this.component=comp;

    11. this.getIncidentInfo=getIncidentInfo;

    12. function getIncidentInfo()

    13. {

    14. return ("Incident: #" + this.incidentnumber + "" + "Priority: " + this.priority + "Support Name: " +

    this.processor + "" + "Customer:" + this.customer);

    15. }

    16. }

    17. var incidentObj = new incident("20132","High","Ali Chalhoub","SAP IT","MOB-ODP");

    18. document.write(incidentObj.getIncidentInfo());

    19.

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 51 Internal

    Whats Array in JavaScript?

    Array Object

    Is a storage for many values ( i.e a List of items )

    To create an Array in JavaScript, do the following:

    var myIncidents = new Array();

    myIncidents[0] = "21022";

    myIncidents[1] = "2134";

    myIncidents[2] = "34312";

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 52 Internal

    Syntax Creating an Array

    There are many ways you can create an Array in JavaScript

    Regular way:

    Condensed way:

    Literal way:

    var myIncidents= new Array();

    myIncidents[0] = "21022";

    myIncidents[1] = "4323";

    var myIncidents = Array{"21022","4323", "43221", "32123"};

    var myIncidents = ["21022","4323", "43221", "32123"];

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 53 Internal

    Ex9 Accessing an Array

    1.

    2.

    3.

    4.

    5. var i;

    6. var myIncidents = new Array();

    7. myIncidents[0] = "21022";

    8. myIncidents[1] = "2134";

    9. myIncidents[2] = "34312";

    10.for (i=0;i

  • Demo - JavaScript and HTML 5

  • JavaScript Best Practice

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 56 Internal

    Tip #1

    Uninitialized variable math is slower by 70%

    Bad:

    var foo;

    foo = 6 + 5;

    Very Bad:

    var foo;

    while (x) { foo++; }

    Good:

    var foo = 0;

    foo = 6 + 5;

    The (arithmetic) operator must determine the variable type each time it does its job,

    so initialized variables generate additional overhead during execution

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 57 Internal

    Tip #2

    Integer comparisons are 20x slower than checking for 0

    Bad:

    for (i < 20) { do x; i++; }

    Good:

    var i = 20;

    while (i--) { do x; }

    Each time you iterate through the loop you need to compare the value of i with 20

    versus comparing i to 0 (the while condition)

    Bottom Line: decrementing WHILE loops is 20x faster than FOR loops

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 58 Internal

    Tip #3

    Finding a DOM elements properties is slow

    Declare an object if youll be accessing it multiple times

    Bad:

    while (cnt--) {document.form1.field1.value = cnt; }

    Good: var aField = document.form1.field1;

    while (cnt--) { aField.value = cnt; };

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 59 Internal

    Tip #4

    document.getElementById() is especially slow and especially popular

    Cache the result

    Avoid calling it inside loops

    Bad: while (cnt--) {

    document.getElementByID(field1).value = cnt;

    }

    Good: var aField = document.getElementByID(field1);

    while (cnt--) {

    aField.value = cnt;

    };

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 60 Internal

    Watch for Function Redeclaration

    Redeclaring functions is legal in JavaScript

    File 1 function modify(x) {

    x = x -5;

    }

    File 2 function modify(x) {

    x = x + 5

    }

    Which modify function does it use?

    var result = modify(10)

    If each of these modify functions are defined in different JavaScript files and included by others it is very difficult to determine why you are getting unexpected results

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 61 Internal

    Utility Classes

    Create classes for every [group of] functions (i.e. Utility classes)

    Instead of calling

    var result = modify(10);

    Each function will be called as

    var util = new Utility();

    var result = util.modify(10);

    Always know which class holds the function you called

    No naming conflicts

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 62 Internal

    Global Classes

    A naming standard can help with reading code and understanding scope

    function modify(x) {

    x = gMyClass.increment(x)

    }

    At a glance you know gMyClass was defined as a global class and it will be found in MyClass.js file

  • 2014 SAP AG or an SAP affiliate company. All rights reserved. 63 Internal

    Summary

    We have learned

    What Javascript is and how to create a JS file.

    How to reference an external JavaScript file.

    How to alter an HTML element in JavaScript.

    What JavaScript Object is and how to define one.

    What JavaScript Array Object is and how to use it.

    The best recommended JavaScript coding.

  • 2014 SAP AG or an SAP affiliate company. All rights reserved.

    Thank you

    Contact information:

    Ali Chalhoub

    Global Architect NEXUS Support Engineer

    Waterloo, ON CA