Download - Chapter 7 JVS
-
7/27/2019 Chapter 7 JVS
1/65
JavaScript
Ken Ratri. MT
KR-2012
Desain Web IF-1P03
1
-
7/27/2019 Chapter 7 JVS
2/65
Introduction
JavaScript is THE scripting language of the Web. JavaScript is used in billions of Web pages to add functionality,
validate forms, communicate with the server, and much more.
A scripting language is a lightweight programming language.
JavaScript was designed to add interactivity to HTML pages. JavaScript is programming code that can be inserted into
HTML pages to be executed by the web browser.
Many HTML designers are not programmers, but JavaScript is a
language with a very simple syntax. Almost anyone can putsmall "snippets" of JavaScript code into HTML pages.
KR-20122
-
7/27/2019 Chapter 7 JVS
3/65
Introduction
JavaScript can: Write directly to the HTML output stream
Change the content or style of HTML elements
React to HTML events and test HTML form input
Delete and create HTML elements
KR-20123
-
7/27/2019 Chapter 7 JVS
4/65
Introduction
ECMA-262 is the official name of the JavaScript standard. JavaScript was invented by Brendan Eich at Netscape, and
appeared for the first time in Netscape Navigator (a no longerexisting web browser) in 1995.
The JavaScript standard was adopted by the industry standardassociation ECMA in 1997.
The development of the standard (ECMAScript-262) is a workin progress.
KR-20124
-
7/27/2019 Chapter 7 JVS
5/65
Introduction
JavaScript and Java are two completely different languages, inboth concept and design.Java (developed by Sun) is acomplex programming language inthe category as C and C++.
KR-20125
-
7/27/2019 Chapter 7 JVS
6/65
JavaScript How To
Scripts in HTML must be inserted between and tags.
Scripts can be put in the and in the section of an HTML page.
Scripts can also be placed in external files. External filesoften contain code to be used by several different webpages. External JavaScript files have the file extension .js.
KR-20126
-
7/27/2019 Chapter 7 JVS
7/65
How To
Scripts in HTML must be inserted between and tags.
Scripts can be put in the and in the section ofan HTML page.
KR-20127
// JavaScript code
-
7/27/2019 Chapter 7 JVS
8/65
The Tag
To insert a JavaScript into an HTML page, use the tag. The and tells where the JavaScript starts
and ends.
The lines between the and contain the
JavaScript:
KR-20128
alert("My First JavaScript");
-
7/27/2019 Chapter 7 JVS
9/65
JavaScript in
KR-20129
My Web Page
A Paragraph
document.getElementById("demo").innerHTML="My First JavaScript";The JavaScript is placed at the bottom of the page to make sure it is executed afterthe
element is created.
-
7/27/2019 Chapter 7 JVS
10/65
Scripts dalam and
KR-2012
....
....
10
-
7/27/2019 Chapter 7 JVS
11/65
To use an external script, point to the .js file
in the "src" attribute of the tag:
KR-2012
External scripts cannot contain tags.
11
-
7/27/2019 Chapter 7 JVS
12/65
JavaScript Statements
JavaScript statements are "commands" to the browser.The purpose of the statements is to tell the browserwhat to do.
This JavaScript statement tells the browser to write Test
Id " inside an HTML element with id="demo":
KR-201212
document.getElementById("demo").innerHTML=Test Id";
Semicolon ;Semicolon separates JavaScript statements.
Normally you add a semicolon at the end of each executable statement.
Using semicolons also makes it possible to write many statements on one line.
-
7/27/2019 Chapter 7 JVS
13/65
JavaScript Code
is a sequence of JavaScript statements.
Each statement is executed by the browser in the sequence they are written.
This example will manipulate two HTML elements:
KR-201213
My Web Page
A Paragraph.
A DIV.
document.getElementById("demo").innerHTML="Hello ;document.getElementById("myDIV").innerHTML="How are you?";
-
7/27/2019 Chapter 7 JVS
14/65
JavaScript Statements
JavaScript is case sensitive.Ex.document.write("This is a heading");document.write("
This is a paragraph.
");document.write("This is another paragraph.
");JavaScript statements can be grouped together in blocks.{document.write("This is a heading");document.write("
This is a paragraph.
");document.write("This is another paragraph.
");}KR-201214
-
7/27/2019 Chapter 7 JVS
15/65
JavaScript Statements
JavaScript ignores extra spaces. You can add white spaceto your script to make it more readable. The followinglines are equivalent:
KR-201215
var name="Hege";
var name = "Hege";
-
7/27/2019 Chapter 7 JVS
16/65
Comments
Single line comments, start //Multi line comments start /* and end with */
KR-2012
// Write a heading
document.write("This is a heading");// Write two paragraphs:document.write("
This is a paragraph.
");/*The code below will writeone heading and two paragraphs*/document.write("
This is another paragraph.
");16
-
7/27/2019 Chapter 7 JVS
17/65
Write to the HTML Output Stream
KR-2012
JavaScript can write directly into the HTML output stream:
document.write("
This is a paragraph.
");17
-
7/27/2019 Chapter 7 JVS
18/65
change HTML Content
KR-2012
JavaCript chan change the content of an HTML element.
x=document.getElementById("demo"); // Find an elementx.innerHTML="Hello"; // Change the content
18
-
7/27/2019 Chapter 7 JVS
19/65
React to Events
KR-2012
My First JavaScript
JavaScript can react to events. Like the click of a button.
function myFunction(){document.getElementById("demo").innerHTML="Hello JavaScript!";}Click Me!
19
-
7/27/2019 Chapter 7 JVS
20/65
Change HTML Styles
KR-2012
My First JavaScript
JavaScript can react to events. Like the click of a button.
function myFunction(){document.getElementById("demo").innerHTML="Hello JavaScript!";}Click Me!
20
-
7/27/2019 Chapter 7 JVS
21/65
Test Input
KR-2012
My First JavaScript
function myFunction(){if(isNaN(document.getElementById("demo").value))
{alert("Not Numeric");
}}Click Me!
21
-
7/27/2019 Chapter 7 JVS
22/65
Variables &Operators JavaScript variables are "containers" for storing information:
KR-2012
var x=5;var y=6;
var z=5+6;
document.write(x + "
");document.write(y + "
");document.write(z + "
");22
-
7/27/2019 Chapter 7 JVS
23/65
Variables &Operators Variable can have short names (like x and y) or more descriptive names (age, sum,
totalvolume). Variable names must begin with a letter
Variable names can also begin with $ and _ (but we will not use it)
Variable names are case sensitive (y and Y are different variables)
KR-201223
Variable note
Contoh_3.1 True
_contoh3.2 True
2001_angkatan False
$sql False
-
7/27/2019 Chapter 7 JVS
24/65
Declaring (Creating) Variables
In the example below we create a variable calledcarname, assigns the value "Volvo" to it, and put the valueinside the HTML paragraph with id="demo":
KR-201224
var carname="Volvo";document.getElementById("demo").innerHTML=carname; -
7/27/2019 Chapter 7 JVS
25/65
One Statement, Many Variables
You can declare many variables in one statement. Just start thestatement with varand separate the variables by comma:
KR-201225
var name="Doe", age=30, job="carpenter";
var name="Doe",age=30,
job="carpenter";
Your declaration can also span multiple lines:
-
7/27/2019 Chapter 7 JVS
26/65
Data Types
String, Number, Boolean, Array, Object, Null, Undefined. A string can be any text inside quotes. You can use simple
or double quotes:
KR-201226
var carname="Volvo XC60";var carname='Volvo XC60';
var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';
-
7/27/2019 Chapter 7 JVS
27/65
JavaScript Data Types
JavaScript variables can also hold other types of data, like text values
(name=Andrew Benjamin").
In JavaScript a text like " Andrew Benjamin " is called a string.
When you assign a text value to a variable, put double or single quotesaround the value.
When you assign a numeric value to a variable, do not put quotes aroundthe value. If you put quotes around a numeric value, it will be treated astext.
KR-201227
var pi=3.14;var name=Andrew Benjamin";var answer='Yes I am!';
-
7/27/2019 Chapter 7 JVS
28/65
Data Types
Numbers JavaScript has only one type of numbers. Numbers can be
written with, or without decimals:
KR-201228
var x1=34.00; //Written with decimals
var x2=34; //Written without decimals
var y=123e5; // 12300000var z=123e-5; // 0.00123
-
7/27/2019 Chapter 7 JVS
29/65
Data Types
Booleans
Booleans can only have two values: true or false.
Booleans are often used in conditional testing. You willlearn more about conditional testing in a later chapter of
this tutorial.
KR-201229
var x=truevar y=false
T
-
7/27/2019 Chapter 7 JVS
30/65
Data Types
Arrays
The following code creates an Array called cars:
KR-201230
var cars=new Array();cars[0]="Saab";cars[1]="Volvo";
cars[2]="BMW";
or (condensed array):
var cars=new Array("Saab","Volvo","BMW");
or (literal array):
var cars=["Saab","Volvo","BMW"];
D T
-
7/27/2019 Chapter 7 JVS
31/65
Data Types
Objects
An object is delimited by curly braces. Inside the braces theobject's properties are defined as name and value pairs (name :value). The properties are separated by commas:
KR-201231
var person={firstname:"John", lastname:"Doe", id:5566};
The object (person) in the example above has 3 properties: firstname,
lastname, and id.
Spaces and line breaks are not important. Your declaration can span
multiple lines:
var person={firstname : "John",lastname : "Doe",id : 5566};
D t T
-
7/27/2019 Chapter 7 JVS
32/65
Data Types
Undefined and Null
Undefined is the value of a variable with no value.
Variables can be emptied by setting the value to null;
KR-201232
cars=null;person=null;
Declaring Variable Types
When you declare a new variable, you can declare its type using the "new"
keyword:
var carname=new String;var x= new Number;var y= new Boolean;var cars= new Array;var person= new Object;
J S i t Obj t
-
7/27/2019 Chapter 7 JVS
33/65
JavaScript Objects
"Everything" in JavaScript is an Object: a String, a Number,an Array, a Date....
An object is just a special kind of data, with propertiesand methods.
Properties are the values associated with an object. Methods are the actions that can be performed on
objects.
KR-201233
J S i t Obj t
-
7/27/2019 Chapter 7 JVS
34/65
JavaScript Objects
Objects in Real Life:
If a car is an object:
The properties of the car include name, model, weight,color, etc.
All cars have these properties, but the values of thoseproperties differ from car to car.
The methods of the car could be start(), drive(), brake(),etc.
All cars have these methods, but they are performed atdifferent times.
KR-201234
-
7/27/2019 Chapter 7 JVS
35/65
KR-201235
Properties:
name=Fiat
model=500
weight=850kg
color=white
Methods:
start()
drive()
brake()
-
7/27/2019 Chapter 7 JVS
36/65
KR-201236
Hello
Properties:
length=5
Methods:
indexOf()
replace()
search()
C ti Obj t
-
7/27/2019 Chapter 7 JVS
37/65
Creating Objects
JavaScript has several built-in objects, like String, Date,Array, and more.
You can also create your own objects.
This example creates an object, and adds four properties
to it:
KR-201237
personObj=new Object();personObj.firstname="John";personObj.lastname="Doe";personObj.age=50;personObj.eyecolor="blue";
A i g Obj t P ti
-
7/27/2019 Chapter 7 JVS
38/65
Accessing Object Properties
The syntax for accessing the property of an object is:
KR-201238
objectName.propertyName
This example uses the length property of the String object to find the
length of a string:
var message="Hello World!";var x=message.length;
The value of x, after execution of the code above will be:
12
Accessing Object Methods
-
7/27/2019 Chapter 7 JVS
39/65
Accessing Object Methods
The syntax for accessing the method :
KR-201239
objectName.methodName()
This example uses the toUpperCase() method of the String object, to
convert a text to uppercase:
var message="Hello world!";var x=message.toUpperCase();
The value of x, after execution of the code above will be:
HELLO WORLD!
-
7/27/2019 Chapter 7 JVS
40/65
Function A function is a block of code that will be executed when "someone" calls it
A function is written as a code block (inside curly { } braces), preceded bythe function keyword:
KR-2012
function functionname()
{some code to be executed}
40
-
7/27/2019 Chapter 7 JVS
41/65
Calling a Function with Arguments When you call a function, you can pass along some values to it, these values
are called arguments or parameters. These arguments can be used inside the function.
You can send as many arguments as you like, separated by commas (,)
KR-2012
myFunction(argument1,argument2)
41
Declare the argument, as variables, when you declare the function:
function myFunction(var1,var2)
{some code}
-
7/27/2019 Chapter 7 JVS
42/65
Functions With a Return Value
Sometimes you want your function to return a value back to where the call
was made.
This is possible by using the return statement.
When using the return statement, the function will stop executing, andreturn the specified value.
Syntax
KR-201242
function myFunction(){var x=5;return x;}
The function above will return the value 5.
-
7/27/2019 Chapter 7 JVS
43/65
Functions With a Return Value
You can also use the returnvalue without storing it as a variable:
KR-201243
document.getElementById("demo").innerHTML=myFunction();
function myFunction(a,b){return a*b;}
document.getElementById("demo").innerHTML=myFunction(4,3);
Example
Calculate the product of two numbers, and return the result:
-
7/27/2019 Chapter 7 JVS
44/65
Operators
KR-2012
Operator Description Example Result
+ Addition x=y+2 x=7- Subtraction x=y-2 x=3* Multiplication x=y*2 x=10/ Division x=y/2 x=2.5% Modulus (division
remainder)
x=y%2 x=1
++ Increment x=++y x=6-- Decrement x=--y x=4
As with algebra, you can do arithmetic with JavaScript variables, using
operators like = and +:
44
-
7/27/2019 Chapter 7 JVS
45/65
Assignment Operators
KR-2012
Assignment operators are used to assign values to JavaScript variables.
Given that x=10 and y=5, the table below explains the assignment operators:
Operator Example Same As Result
= x=y x=5
+= x+=y x=x+y x=15
-= x-=y x=x-y x=5
*= x*=y x=x*y x=50
/= x/=y x=x/y x=2%= x%=y x=x%y x=0
45
The + Operator Used on Strings
-
7/27/2019 Chapter 7 JVS
46/65
The + Operator Used on Strings
The + operator can also be used to add string variablesor text values together.
Ex.
KR-201246
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
What a verynice day
-
7/27/2019 Chapter 7 JVS
47/65
Adding Strings and Numbers
Adding two numbers, will return the sum, but adding anumber and a string will return a string:
KR-201247
x=5+5;
y="5"+5;
z="Hello"+5;
1055
Hello5
Comparison Operators
-
7/27/2019 Chapter 7 JVS
48/65
Comparison Operators
KR-2012
Operator Description Example== is equal to x==8 is false
=== is exactly equal to (valueand type)
x===5 is truex==="5" is false
!= is not equal x!=8 is true> is greater than x>8 is false
< is less than x= is greater than or equalto
x>=8 is false
-
7/27/2019 Chapter 7 JVS
49/65
Logical Operators
KR-2012
Logical operators are used to determine the logic between variables or values.
Given that x=6 and y=3, the table below explains the logical operators:
Operator Description Example
&& and (x < 10 && y > 1) istrue
|| or (x==5 || y==5) isfalse
! not !(x==y) is true
49
Conditional Operator
-
7/27/2019 Chapter 7 JVS
50/65
Conditional Operator
JavaScript also contains a conditional operator thatassigns a value to a variable based on some condition.
Syntax
KR-201250
variablename=(condition)?value1:value2
Ex
voteable=(age
-
7/27/2019 Chapter 7 JVS
51/65
If...Else Statements Very often when you write code, you want to perform
different actions for different decisions. You can use conditionalstatements in your code to do this.
In JavaScript we have the following conditional statements:
if statement - use this statement to execute some code only
if a specified condition is true
if...else statement - use this statement to execute somecode if the condition is true and another code if the conditionis false
if...else if....else statement - use this statement to selectone of many blocks of code to be executed
switch statement - use this statement to select one of manyblocks of code to be executed
KR-201251
-
7/27/2019 Chapter 7 JVS
52/65
If Statement
KR-2012
if (condition){
code to be executed if condition is true
}
if (condition){code to be executed if condition is true}
else{code to be executed if condition is not true}
52
-
7/27/2019 Chapter 7 JVS
53/65
If...else if...else Statement
KR-2012
if (condition1){code to be executed if condition1 is true}
else if (condition2){code to be executed if condition2 is true}
else{code to be executed if condition1 and condition2 are not true}
53
-
7/27/2019 Chapter 7 JVS
54/65
Switch Statement
KR-2012
switch(n){case 1:
execute code block 1break;
case 2:execute code block 2
break;default:code to be executed if n is different from case 1 and 2
}
54
Use the switch statement to select one of many blocks of code to be
executed.
-
7/27/2019 Chapter 7 JVS
55/65
Loop Loops are handy, if you want to run the same code over and over again,
each time with a different value.
KR-2011
document.write(cars[0] + "
");document.write(cars[1] + "
");document.write(cars[2] + "
");document.write(cars[3] + "
");document.write(cars[4] + "
");document.write(cars[5] + "
");for (var i=0;i
-
7/27/2019 Chapter 7 JVS
56/65
Loop
Different Kinds of Loops
JavaScript supports different kinds of loops:
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 specifiedcondition is true
do/while - also loops through a block of code while a
specified condition is true
KR-2011
-
7/27/2019 Chapter 7 JVS
57/65
For...In Statement
The for loop is often the tool you will use when you wantto create a loop.
The for loop has the following syntax:
KR-2011
for (statement 1; statement 2; statement 3){the 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.
-
7/27/2019 Chapter 7 JVS
58/65
KR-201258
for (var i=0; i
-
7/27/2019 Chapter 7 JVS
59/65
The For/In Loop
The JavaScript for/in statement loops through theproperties of an object:
KR-201259
var person={fname:"John",lname:"Doe",age:25};
for (x in person){
txt=txt + person[x];
}
While Loop
-
7/27/2019 Chapter 7 JVS
60/65
While Loop
The while loop loops through a block of code as long as aspecified condition is true.
KR-201260
while (condition)
{code block to be executed}
While Loop
-
7/27/2019 Chapter 7 JVS
61/65
While Loop
KR-201261
while (i
-
7/27/2019 Chapter 7 JVS
62/65
The Do/While Loop
The do/while loop is a variant of the while loop. This loopwill execute the code block once, before checking if thecondition is true, then it will repeat the loop as long asthe condition is true.
KR-201262
do{code block to be executed
}while (condition);
The Do/While Loop
-
7/27/2019 Chapter 7 JVS
63/65
/ p
KR-201263
do{x=x + "The number is " + i +
"
";i++;}
while (i
-
7/27/2019 Chapter 7 JVS
64/65
Break and Continue Statements
he break statement "jumps out" of a loop.
The continue statement "jumps over" one iteration in theloop.
It was used to "jump out" of a switch() statement.
KR-2011
for (i=0;i
-
7/27/2019 Chapter 7 JVS
65/65
Break and Continue Statements
The continue statement breaks one iteration (in theloop), if a specified condition occurs, and continues withthe next iteration in the loop.
This example skips the value of 3:
for (i=0;i