Sie sind auf Seite 1von 105

Java Script

© CSS Corp | Confidential | www.csscorp.com 1 Customer Engagement Reimagined


World Wide Web

© CSS Corp | Confidential | www.csscorp.com 2 Customer Engagement Reimagined


Client Server Architecture

© CSS Corp | Confidential | www.csscorp.com 3 Customer Engagement Reimagined


3
Web Server & Web Browser

© CSS Corp | Confidential | www.csscorp.com 4 Customer Engagement Reimagined


4
Client Side Scripting using JavaScript

© CSS Corp | Confidential | www.csscorp.com 5 Customer Engagement Reimagined


5
Version History*

*(From Wiki Page)

© CSS Corp | Confidential | www.csscorp.com 6 Customer Engagement Reimagined


6
DOM tree

A DOM-tree comprises

Document Node
the root node representing the entire HMTL document.

Element node
represents an HTML element (or tag). An element node may have
child nodes, which can be either element or text node. Element node
may also have attributes.

Text Node: contains the text content of an element.

© CSS Corp | Confidential | www.csscorp.com 7 Customer Engagement Reimagined


Where to place JavaScript?

• Within HTML page


• In separate .js file

© CSS Corp | Confidential | www.csscorp.com 8 Customer Engagement Reimagined


8
Within HTML page

© CSS Corp | Confidential | www.csscorp.com 9 Customer Engagement Reimagined


9
External .js file

© CSS Corp | Confidential | www.csscorp.com 10 Customer Engagement Reimagined


10
JavaScript Programming
• Display methods
• Variables
• Control Structures
• Loops
• Operators
• Arrays
• Data Structures
• Functions
• Event Handling
• Objects
• Object Oriented js

© CSS Corp | Confidential | www.csscorp.com 11 Customer Engagement Reimagined


11
Interacting with users

© CSS Corp | Confidential | www.csscorp.com 12 Customer Engagement Reimagined


12
Display Methods

JavaScript does NOT have any built-in print or display function

• Writing into an alert box, using window.alert()


• Writing into the HTML output using document.write()
• Writing into an HTML element, using innerHTML
• Writing into the browser console, using console.log()

© CSS Corp | Confidential | www.csscorp.com 13 Customer Engagement Reimagined


13
Display Method 1

• Writing into an alert box, using window.alert()


• window.alert("Welcome");

© CSS Corp | Confidential | www.csscorp.com 14 Customer Engagement Reimagined


14
Finding & Selecting elements on DOM

© CSS Corp | Confidential | www.csscorp.com 15 Customer Engagement Reimagined


Display Method 2

• Writing into the HTML output using document.write()


• document.write("Welcome in HTML page");

© CSS Corp | Confidential | www.csscorp.com 16 Customer Engagement Reimagined


16
Inner HTML property

• You can access and modify the content of an element via the "innerHTML" property, which
contains all the texts (includes nested tags) within this element

© CSS Corp | Confidential | www.csscorp.com 17 Customer Engagement Reimagined


17
Display Method 3

• Writing into an HTML element, using innerHTML

• You can access and modify the content of an element via the "innerHTML" property, which
contains all the texts (includes nested tags) within this element

• document.getElementById("msg").innerHTML = "Hello "+ yourName;

© CSS Corp | Confidential | www.csscorp.com 18 Customer Engagement Reimagined


18
Display Method 3 – cont…

© CSS Corp | Confidential | www.csscorp.com 19 Customer Engagement Reimagined


19
Display Method 4

• Writing into the browser console, using console.log()


• console.log(“Welcome message in console”);

Activate the browser console with F12, and select "Console" in the menu to see the result

© CSS Corp | Confidential | www.csscorp.com 20 Customer Engagement Reimagined


20
Comments

• // : single line comment


• /* */ : multiline comment

© CSS Corp | Confidential | www.csscorp.com 21 Customer Engagement Reimagined


21
JavaScript Values

• The JavaScript syntax defines two types of values


• Fixed values - literals
• Variable values - Variables

© CSS Corp | Confidential | www.csscorp.com 22 Customer Engagement Reimagined


22
Literals

• Numbers with or without decimals

Example : document.getElementById("demo").innerHTML = 10.50;

• Strings are text, written within double or single quotes

Example : document.getElementById("demo").innerHTML = ‘javascript';

© CSS Corp | Confidential | www.csscorp.com 23 Customer Engagement Reimagined


23
Identifiers

• All JavaScript variables must be identified with unique names called identifiers.
• Identifiers can be
• Short descriptive names (age, sum, Volume).

The general rules for constructing names for variables (unique identifiers) are:
• Names can contain letters, digits, underscores, and dollar signs.
• Names must begin with a letter
• Names can also begin with $ and _
• Names are case sensitive (y and Y are different variables)
• Reserved words (like JavaScript keywords) cannot be used as names

© CSS Corp | Confidential | www.csscorp.com 24 Customer Engagement Reimagined


24
Variables

• Variables are used to store data values

var is the keyword used to declare variables


= is the symbol to assign values

© CSS Corp | Confidential | www.csscorp.com 25 Customer Engagement Reimagined


25
Variables – cont…

• Variables can hold data belonging to any data type


• Many variables can be declared in one statement
• A variable declared without a value will have the value undefined

Example : 1
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML = z;

Example : 2
var person = “APJ", carName = 'swift', price = 200;
document.getElementById("demo").innerHTML = carName;

© CSS Corp | Confidential | www.csscorp.com 26 Customer Engagement Reimagined


26
Basic Data Types

© CSS Corp | Confidential | www.csscorp.com 27 Customer Engagement Reimagined


27
Data Types - Examples

var length = 16; // Number


var lastName = “Kapoor"; // String
var cars = [“Merc", "Volvo", "BMW"]; // Array
var x = {firstName:“Java", lastName:“Script"}; // Object
var flag = true; //Boolean

© CSS Corp | Confidential | www.csscorp.com 28 Customer Engagement Reimagined


28
Dynamic Types

var x; // Now x is undefined


var x = 5; // Now x is a Number
var x = “JavaScript"; // Now x is a String

© CSS Corp | Confidential | www.csscorp.com 29 Customer Engagement Reimagined


29
Number

© CSS Corp | Confidential | www.csscorp.com 30 Customer Engagement Reimagined


30
Numbers

• Can be with or without decimals


• Extra large or extra small numbers can be written with scientific (exponent) notation
• var x = 123e5; // 12300000
• var y = 123e-5; // 0.00123
• Stores numbers in 64 bits
• number (the fraction) is stored in bits 0 to 51
• exponent in bits 52 to 62
• sign in bit 63
• Integers are accurate up to 15 digits
• Numeric constants are considered as hexadecimal if they are preceded by 0x

© CSS Corp | Confidential | www.csscorp.com 31 Customer Engagement Reimagined


31
HexaDecimal
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "0xFF = " + 0xFF; //255
}
</script>

• By default numbers are considered as base 10 decimals


• toString() method can be used to output numbers as base 16 (hex), base 8 (octal), or base 2 (binary)
• Example
var myNumber = 128;
myNumber.toString(16); // returns 80
myNumber.toString(8); // returns 200
myNumber.toString(2); // returns 10000000

© CSS Corp | Confidential | www.csscorp.com 32 Customer Engagement Reimagined


32
Infinity

Infinity / -Infinity is the value JavaScript will return when a number outside the largest possible number is
calculated

Example : document.write(10/0);

© CSS Corp | Confidential | www.csscorp.com 33 Customer Engagement Reimagined


33
NaN - Not a Number
• NaN is a JavaScript reserved word indicating that a value is not a number
• Trying to do arithmetic with a non-numeric string will result in NaN (Not a Number)

Example : var x = 100 / "Apple";

• If the string contains a numeric value , the result will be a number

Example : document.getElementById("demo").innerHTML = 100 / "10";

• Function isNaN() to find out if a value is a number

Example: var x = 100 / "Apple";


document.getElementById("demo").innerHTML = isNaN(x);

© CSS Corp | Confidential | www.csscorp.com 34 Customer Engagement Reimagined


34
String

© CSS Corp | Confidential | www.csscorp.com 35 Customer Engagement Reimagined


35
String

• JavaScript string simply stores a series of characters


• Can be any text inside quotes
• The length of a string is found in the built in property length
• Example :
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.getElementById("demo").innerHTML = txt.length;

© CSS Corp | Confidential | www.csscorp.com 36 Customer Engagement Reimagined


36
Escape Sequences

© CSS Corp | Confidential | www.csscorp.com 37 Customer Engagement Reimagined


37
String Methods

var msg = "JavaScript is a high-level, dynamic programming language";


document.write("type :" + typeof msg);
document.write(msg.length,"<br/>");
document.write(msg.indexOf("dynamic"),"<br/>");
document.write("sliced data : "+ msg.slice(28,35),"<br/>");
document.write("substring data : "+ msg.substr(28,7),"<br/>");
document.write(msg.fontcolor("red"));
// HTML wrapper methods
document.write(msg.fontsize(".25em").sub().strike().italics());
document.write(msg.toLowerCase(msg.replace("dynamic","best"),"<br/>"));

© CSS Corp | Confidential | www.csscorp.com 38 Customer Engagement Reimagined


38
typeOf Operator

Example:
var msg = "JavaScript is a high-level, dynamic”;
document.write("type :" + typeof msg);

• typeof NaN returns number

© CSS Corp | Confidential | www.csscorp.com 39 Customer Engagement Reimagined


39
String Methods – cont….

© CSS Corp | Confidential | www.csscorp.com 40 Customer Engagement Reimagined


40
String Methods – cont….

© CSS Corp | Confidential | www.csscorp.com 41 Customer Engagement Reimagined


41
Explicit Type Conversion

• Converting a number to a string


Simply concatenate the number with an empty string, e.g., "" + 5 gives "5“

• Converting a string to a number


• Use built-in functions parseInt(string), parseFloat(string) or Number(string) to
convert a string which contains a valid number
• For example, parseInt("55") gives 55
• parseInt(55.66) gives 55
• parseInt("55.66") gives 55
• parseFloat("55.66") gives 55.66
• parseInt("55px") gives 55
• but parseInt("Hello") gives NaN.

• Converting a float to an integer


• Use parseInt() (e.g., parseInt(55.66) gives 55)
• built-in mathematical functions such as Math.round(), Math.ceil() or Math.floor().

© CSS Corp | Confidential | www.csscorp.com 42 Customer Engagement Reimagined


42
Array

• An array is a special variable, which can hold more than one value at a time
• It is a special type of object

<script>
var cars = [“Merc","Volvo","BMW"];
document.getElementById("demo").innerHTML = cars[0];
</script>

© CSS Corp | Confidential | www.csscorp.com 43 Customer Engagement Reimagined


43
Array Methods

var fruits = ["Banana", "Orange", "Apple", "Mango"];

document.getElementById("demo").innerHTML = fruits.toString();
document.getElementById("demo").innerHTML = fruits.join(" * ");
fruits.pop(); // Removes the last element ("Mango") from fruits
var x = fruits.pop(); // the value of x is "Mango“
fruits.push("Kiwi"); // Adds a new element ("Kiwi") to fruits at the end
var x = fruits.push("Kiwi"); // returns the new array length
fruits.shift(); // Removes the first element "Banana" from fruits
fruits.unshift("Lemon"); // Adds a new element "Lemon" to fruits
fruits[0] = "Kiwi"; // Changes the first element of fruits to "Kiwi“
fruits[fruits.length] = "Kiwi"; // Appends "Kiwi" to fruit
delete fruits[0]; // Changes the first element in fruits to undefined

© CSS Corp | Confidential | www.csscorp.com 44 Customer Engagement Reimagined


44
Array Methods

© CSS Corp | Confidential | www.csscorp.com 45 Customer Engagement Reimagined


45
undefined

Variable without a value, has the value undefined

Example:
<script>
var person;
document.getElementById("demo").innerHTML =person + "<br>" + typeof person;
</script>

*In Javascript , null is nothing

© CSS Corp | Confidential | www.csscorp.com 46 Customer Engagement Reimagined


46
Variables – cont…

• When re-declared a JavaScript variable will not lose its value

Example :
<script>
var carName = “Punto";
var carName;
document.getElementById("demo").innerHTML = carName;
</script>

© CSS Corp | Confidential | www.csscorp.com 47 Customer Engagement Reimagined


47
Concatenation

document.write("5+4=", 5+4);

output : 5 +4 = 9

document.write("5+4=“+5+4);

output : 5 + 4 = 54

© CSS Corp | Confidential | www.csscorp.com 48 Customer Engagement Reimagined


48
Arithmetic Operators

© CSS Corp | Confidential | www.csscorp.com 49 Customer Engagement Reimagined


49
Logical Operators

© CSS Corp | Confidential | www.csscorp.com 50 Customer Engagement Reimagined


50
Assignment Operators

© CSS Corp | Confidential | www.csscorp.com 51 Customer Engagement Reimagined


51
Type Operators

© CSS Corp | Confidential | www.csscorp.com 52 Customer Engagement Reimagined


52
Conditional Control
&
Loops

© CSS Corp | Confidential | www.csscorp.com 53 Customer Engagement Reimagined


53
Conditional Control : If .. Else & Switch

• Use if to specify a block of code to be executed, if a specified condition is true


• Use else to specify a block of code to be executed, if the same condition is false
• Use else if to specify a new condition to test, if the first condition is false

© CSS Corp | Confidential | www.csscorp.com 54 Customer Engagement Reimagined


54
© CSS Corp | Confidential | www.csscorp.com 55 Customer Engagement Reimagined
55
© CSS Corp | Confidential | www.csscorp.com 56 Customer Engagement Reimagined
56
If .. Else

© CSS Corp | Confidential | www.csscorp.com 57 Customer Engagement Reimagined


57
If .. Else

© CSS Corp | Confidential | www.csscorp.com 58 Customer Engagement Reimagined


58
If .. Else

© CSS Corp | Confidential | www.csscorp.com 59 Customer Engagement Reimagined


59
Switch

• Use switch to specify many alternative blocks of code to be executed

© CSS Corp | Confidential | www.csscorp.com 60 Customer Engagement Reimagined


60
Looping Structures

• for - loops through a block of code a number of times


• for/in - loops through the properties of an object
• while - loops through a block of code while a specified condition is true
• do/while - also loops through a block of code while a specified condition is true

© CSS Corp | Confidential | www.csscorp.com 61 Customer Engagement Reimagined


61
For

for (statement 1; statement 2; statement 3)


{
code block to be executed
}
Statement 1 is executed before the loop (the code block) starts
Statement 2 defines the condition for running the loop (the code block)
Statement 3 is executed each time after the loop (the code block) has been executed

Example:
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}

© CSS Corp | Confidential | www.csscorp.com 62 Customer Engagement Reimagined


62
For – cont…

var cars = ["BMW", "Volvo", "Saab", "Ford"];


var i = 2; var i = 0;
var len = cars.length; var len = cars.length;
var text = ""; for (; i < len; )
for (; i < len; i++) {
{ text += cars[i] + "<br>";
text += cars[i] + "<br>"; i++;
} }

© CSS Corp | Confidential | www.csscorp.com 63 Customer Engagement Reimagined


63
For/In Loop

var person = {fname:"John", lname:"Doe", age:25};

var text = "";


var x;
for (x in person) {
text += person[x];
}

© CSS Corp | Confidential | www.csscorp.com 64 Customer Engagement Reimagined


64
While Loop

while (condition) {
code block to be executed
}

Example :
while (i < 10) {
text += "The number is " + i;
i++;
}

© CSS Corp | Confidential | www.csscorp.com 65 Customer Engagement Reimagined


65
Do..While Loop

do {
code block to be executed
}
while (condition);

Example :
do {
text += "The number is " + i;
i++;
}
while (i < 10);

© CSS Corp | Confidential | www.csscorp.com 66 Customer Engagement Reimagined


66
Break Statement

• Break statement can be used to jump out of a loop


• Break statement breaks the loop and continues executing the code after the
loop

for (i = 0; i < 10; i++)


{
if (i === 3) { break; }
text += "The number is " + i + "<br>";
}

© CSS Corp | Confidential | www.csscorp.com 67 Customer Engagement Reimagined


67
Continue Statement

• Continue statement breaks one iteration and continues with the next
iteration in the loop

Example:

var text = "";


var i;
for (i = 0; i < 10; i++) {
if (i === 3) { continue; }
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;

© CSS Corp | Confidential | www.csscorp.com 68 Customer Engagement Reimagined


68
Labels

• label: statements
var cars = ["BMW", "Volvo", "Saab", "Ford"];
list:
• Example {
text += cars[0] + "<br>";
break labelname; text += cars[1] + "<br>";
text += cars[2] + "<br>";
continue labelname; break list;
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";
}

© CSS Corp | Confidential | www.csscorp.com 69 Customer Engagement Reimagined


69
Functions

© CSS Corp | Confidential | www.csscorp.com 70 Customer Engagement Reimagined


70
Function

Function Declaration Function Expression

© CSS Corp | Confidential | www.csscorp.com 71 Customer Engagement Reimagined


71
Function
function functionName(parameters)
{
code to be executed
}

Example:
function myFunction(a, b)
{
return a * b;
}

let r = myFunction(10,20);

© CSS Corp | Confidential | www.csscorp.com 72 Customer Engagement Reimagined


72
Function

© CSS Corp | Confidential | www.csscorp.com 73 Customer Engagement Reimagined


73
Anonymous Functions

• A JavaScript function can also be defined using an expression.


• A function expression can be stored in a variable

• Example
var x = function (a, b) {return a * b};
var z = x(4, 3);

© CSS Corp | Confidential | www.csscorp.com 74 Customer Engagement Reimagined


74
Self-Invoking Functions

<script>
(function () {
document.getElementById("demo").innerHTML = "Hello! I called myself";
})();
</script>

© CSS Corp | Confidential | www.csscorp.com 75 Customer Engagement Reimagined


75
Function Parameters and Arguments

• Function parameters are the names listed in the function definition.


• Function arguments are the real values passed to (and received by) the function.

Rules
• JavaScript function definitions do not specify data types for parameters
• JavaScript functions do not perform type checking on the passed arguments
• JavaScript functions do not check the number of arguments received
• If a function is called with missing arguments (less than declared), the missing values are set to: undefined

© CSS Corp | Confidential | www.csscorp.com 76 Customer Engagement Reimagined


76
Arguments Object
• Have built-in object called the arguments object
• Contains an array of the arguments used when the function was called

• Example

x = sumAll(1, 123, 500, 115, 44, 88);

function sumAll() {
var i, sum = 0;
for (i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}

© CSS Corp | Confidential | www.csscorp.com 77 Customer Engagement Reimagined


77
Function as a Object Method
• Functions can be defined as object methods

<script>
var myObject = {
firstName:“Java",
lastName: “Script",
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
document.getElementById("demo").innerHTML = myObject.fullName();
</script>

© CSS Corp | Confidential | www.csscorp.com 78 Customer Engagement Reimagined


78
Invoking a Function with a Function Constructor
• A function invocation is preceded with the new keyword, it is a constructor invocation.

<script>
function myFunction(arg1, arg2) {
this.firstName = arg1;
this.lastName = arg2;
}

var x = new myFunction("Java",“Script")


document.getElementById("demo").innerHTML = x.firstName;
</script>

© CSS Corp | Confidential | www.csscorp.com 79 Customer Engagement Reimagined


79
Variable Lifetime

• Global variables live as long as your


application lives
• Local variables have short lives

© CSS Corp | Confidential | www.csscorp.com 80 Customer Engagement Reimagined


80
JavaScript Nested Functions
• Nested functions have access to the scope "above" them

© CSS Corp | Confidential | www.csscorp.com 81 Customer Engagement Reimagined


81
Callback Functions

© CSS Corp | Confidential | www.csscorp.com 82 Customer Engagement Reimagined


82
Event Handling

© CSS Corp | Confidential | www.csscorp.com 83 Customer Engagement Reimagined


83
Handling Events

• JavaScript are often event-driven

• Events:
• click: generated when the user clicks on an HTML element.
• mouseover, mouseout : generated when the user positions the mouse pointer inside/away from
the HTML element.
• load, unload: generated after the browser loaded a document, and before the next document is
loaded, respectively.
• Event Handler:
• A piece of program that fires in response to a certain user's or browser's action
• The event handler is typically attached to the target HTML tag, e.g.,

© CSS Corp | Confidential | www.csscorp.com 84 Customer Engagement Reimagined


84
Events

© CSS Corp | Confidential | www.csscorp.com 85 Customer Engagement Reimagined


85
Form Validation

© CSS Corp | Confidential | www.csscorp.com 86 Customer Engagement Reimagined


86
Validation of form controls

© CSS Corp | Confidential | www.csscorp.com 87 Customer Engagement Reimagined


87
Validation of form controls – cont…

© CSS Corp | Confidential | www.csscorp.com 88 Customer Engagement Reimagined


88
Validation of form controls – cont…

© CSS Corp | Confidential | www.csscorp.com 89 Customer Engagement Reimagined


89
Object Oriented Programming

© CSS Corp | Confidential | www.csscorp.com 90 Customer Engagement Reimagined


90
Object Basics

• An object is a collection of related data and/or functionality


• variables - properties
• functions - methods

© CSS Corp | Confidential | www.csscorp.com 91 Customer Engagement Reimagined


Object

<script>

var person = {
firstName : “MK",
lastName : “Gandhi",
age: 78,
eyeColor : “Hazel"
};

document.getElementById("demo").innerHTML = person.firstName + " is " + person.age + " years old.";


</script>

© CSS Corp | Confidential | www.csscorp.com 92 Customer Engagement Reimagined


92
Object – sample 2

© CSS Corp | Confidential | www.csscorp.com 93 Customer Engagement Reimagined


93
this

© CSS Corp | Confidential | www.csscorp.com 94 Customer Engagement Reimagined


94
Object Oriented Programming

• Encapsulation
• By Defining an Object template
• Most of OOP languages call it a CLASS

© CSS Corp | Confidential | www.csscorp.com 95 Customer Engagement Reimagined


95
Implementation using Java Script

• The constructor function is JavaScript's version of a class

© CSS Corp | Confidential | www.csscorp.com 96 Customer Engagement Reimagined


96
Instantiation

• Process of creating actual


Objects or instances

© CSS Corp | Confidential | www.csscorp.com 97 Customer Engagement Reimagined


Implementation using Java Script

• New keyword is used for instantiation

© CSS Corp | Confidential | www.csscorp.com 98 Customer Engagement Reimagined


98
Implementation using Java Script

• Technique 2 : To create an instance using create()

© CSS Corp | Confidential | www.csscorp.com 99 Customer Engagement Reimagined


99
Prototype Based Language

• Prototype Chaining

© CSS Corp | Confidential | www.csscorp.com 100 Customer Engagement Reimagined


100
Inheritance

• In OOP, we can create new


classes based on other classes
• Existing class – parent
class
• New class - child class

• Child class can be made to


inherit the data and code
features of their parent class

© CSS Corp | Confidential | www.csscorp.com 101 Customer Engagement Reimagined


Implementation using Java Script

© CSS Corp | Confidential | www.csscorp.com 102 Customer Engagement Reimagined


102
Setting prototype and constructor reference

Cloning the prototype

© CSS Corp | Confidential | www.csscorp.com 103 Customer Engagement Reimagined


103
Instantiation of Child Class

© CSS Corp | Confidential | www.csscorp.com 104 Customer Engagement Reimagined


Thank You
Customer Engagement Reimagined
Our Locations: U.S.A | U.K | China | Costa Rica | India | Mauritius | Philippines | Poland | Singapore

© CSS Corp | Confidential | www.csscorp.com 105 Customer Engagement Reimagined

Das könnte Ihnen auch gefallen