0% found this document useful (0 votes)
6 views

Website JavaScript

Uploaded by

innosamwel445
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Website JavaScript

Uploaded by

innosamwel445
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 50

The JavaScript Language

1
Objectives
• Learn about JavaScript
• Using JavaScript in HTML
• Language Elements
• Variables
• Operators
• Control Statements
• Functions
• Objects
• Exception handling.

2
About JavaScript
• JavaScript is not Java, or even related to Java
• The original name for JavaScript was “LiveScript”
• The name was changed when Java became popular
• Statements in JavaScript resemble statements in Java,
because both languages borrowed heavily from the C
language
• JavaScript should be fairly easy for Java programmers to learn
• However, JavaScript is a complete, full-featured, complex language
• JavaScript is seldom used to write complete “programs”
• Instead, small bits of JavaScript are used to add functionality to
HTML pages
• JavaScript is usually embedded directly into HTML pages
3
About JavaScript
• JavaScript was designed to add interactivity to HTML
pages
• JavaScript is a scripting language (a scripting language is
a lightweight programming language)
• A JavaScript consists of lines of executable computer
code
• JavaScript is an interpreted language (means that scripts
execute without preliminary compilation)
• Everyone can use JavaScript without purchasing a license

4
Why use JavaScript?
• To add dynamic function to your HTML.
– JavaScript does things that HTML can’t—like logic.
– You can change HTML on the fly.
• To remove some of the form-processing burden.
– JavaScript runs in the browser, not on the Web server.
• Better performance
– JavaScript can validate the data that users enter into the form,
before it is sent to your Web application.

5
Using JavaScript in a browser
• JavaScript code is included within <script> tags:
– <script type="text/javascript">
document.write("<h1>Hello World!</h1>") ;
</script>
• Notes:
• The type attribute is to allow you to use other scripting languages
(but JavaScript is the default)
• This simple code does the same thing as just putting <h1>Hello
World!</h1> in the same place in the HTML document
• The semicolon at the end of the JavaScript statement is optional
• You need semicolons if you put two or more statements on the same
line
• It’s probably a good idea to keep using semicolons 6
Where to put JavaScript
• JavaScript can be put in the <head> or in the <body> of
an HTML document
• JavaScript functions should be defined in the <head>???
• This ensures that the function is loaded before it is needed
• JavaScript in the <body> will be executed as the page loads
• JavaScript can be put in a separate .js file
– <script src="myJavaScriptFile.js"></script>
• Put this HTML wherever you would put the actual JavaScript code
• An external .js file lets you use the same JavaScript on multiple
HTML pages
• The external .js file cannot itself contain a <script> tag
7
• JavaScript can be put in HTML form object, such as a button
• This JavaScript will be executed when the form object is used
Language Elements
• Variables
• Operators
• Control Statements
• Functions
• Objects

8
JavaScript Variables
• Untyped!(Implicit) :
foo = 6;

• Can be declared with var keyword (Explicit ):


var foo;

• Can be created automatically by assigning a value:


foo=1; blah="Hi Dave";

9
Variable Scope
• Global
• Declared outside functions
• Any variable implicitly defined

• Local
• Explicit declarations inside functions

• Note
• Variables can hold any valid type of value (Dynamic
Typing ), and can hold values of different types at 10
different times during execution.
Primitive data types
• JavaScript has three “primitive” types: number, string,
and boolean
• Everything else is an object
• Numbers are always stored as floating-point values
• Hexadecimal numbers begin with 0x
• Some platforms treat 0123 as octal, others treat it as decimal
• Strings may be enclosed in single quotes or double
quotes
• Strings can contains \n (newline), \" (double quote), etc.
• Booleans are either true or false
– 0, "0", empty strings, undefined, null, and NaN are false , 11
other values are true
Operators
• Arithmetic, comparison, assignment, bitwise, boolean (pretty
much just like C++).

+ - * / % ++ -- == != > <
&& || ! & | << >>

12
Arithmetic Operators
Operator Description Example Result

+ Addition x=2 4
y=2
x+y
- Subtraction x=5 3
y=2
x-y
* Multiplication x=5 20
y=4
x*y
/ Division 15/5 3
10/3
3.3333333333333335
% Modulus (division 5%2 1
remainder)
10%2 0
2%5 2
++ Increment x=5 x=6
13
x++
-- Decrement x=5 x=4
x--
Assignment Operators
Operator Example Is The Same As

= x=y x=y

+= x+=y x=x+y

-= x-=y x=x-y

*= x*=y x=x*y

/= x/=y x=x/y

%= x%=y x=x%y
14
Comparison Operators
Operator Description Example

== is equal to 5==8 returns false

=== is equal to (checks for both value x=5


and type)
y="5"

x==y returns true

x===y returns false

!= is not equal 5!=8 returns true

> is greater than 5>8 returns false

< is less than 5<8 returns true

>= is greater than or equal to 5>=8 returns false

<= is less than or equal to 5<=8 returns true


15
Logical Operators
Operator Description Example

&& and x=6

y=3

(x < 10 && y > 1) returns true

|| or x=6

y=3

(x==5 || y==5) returns false

! not x=6

y=3

16
!(x==y) returns true
Different from C++
• The + operator is used for addition (if both operands are
numbers)
-or-
• The + operator means string concatenation (if either one of the
operands is not a number)

17
Comments
• Comments are as in C or Java:
• Between // and the end of the line
• Between /* and */
• Java’s javadoc comments, /** ... */, are treated just the same
as /* ... */ comments; they have no special meaning in
JavaScript

18
Control Statements, I
• Most JavaScript statements are also borrowed from C
• Assignment: greeting = "Hello, " + name;
• Compound statement:
{ statement; ...; statement }
• If statements:
if (condition) statement;
if (condition) statement; else statement;
• Familiar loop statements:
while (condition) statement;
do statement while (condition);
for (initialization; condition; increment) statement;

19
Control Statements, II
• The switch statement:
switch (expression){
case label :
statement;
break;
case label :
statement;
break;
...
default : statement;
}
• Other familiar statements:
– break;
– continue;
• The empty statement, as in ;; or { } 20
Control Statements, III
• And few not in C
for (var in object)

with (object)

21
Javascript Functions
• The keyword function is used to define a function
(subroutine):

function add(x,y) {
return(x+y);
}
• No type is specified for arguments!

22
What is the value of:

add(3,4) 7

add(“3”,”4”) 34

add(“Hi”,”Dave”) “HiDave”

add(3,”Hi”) “3Hi”

add(“2.13blah”,3.14 “2.13blah3.14”
23
)
Javascript program
<SCRIPT>
function add(x,y) {
return(x+y);
}

document.write("add(3,4) is " + add(3,4) + "<BR>");


document.write("add(\"3\",\"4\") is " + add("3","4") +
"<BR>");
document.write("add(\"Hi\",\"Dave\") is " +
add("Hi","Dave") + "<BR>");
document.write("add(3,\"Hi\") is " + add(3,"Hi") +
"<BR>");
document.write("add(\"2.13blah\",3.14) is " +
add("2.13blah",3.14)); 24
</SCRIPT>
JavaScript Global Functions
Function Description
escape() Encodes a string that is not in ASCII character set
e.g. document.write(escape(“Hello! World.”))

eval() Evaluates a string and executes it as if it was script


code e.g. document.write("<br>" + eval("2+2"));

isFinite() Determines whether a value is a finite, legal number


Eg isFinite(123)-> true, isFinite("Hello")-> false

isNaN() Determines whether a value is an illegal number


Eg isNaN(123)-> false, isNaN("Hello")-> true

Number() Converts an object's value to a number


parseFloat() Parses a string and returns a floating point number

parseInt() Parses a string and returns an integer 25


String() Converts an object's value to a string
unescape() Decodes an encoded string
Objects in JavaScript
• Objects have attributes and methods.
• Many pre-defined objects and object types.
• Using objects follows the syntax of C++/Java:
objectname.attributename
objectname.methodname()
• JavaScript is not Object Oriented – but Object-
Based
26
Three ways to create an
object
• You can use an object literal:
– var course = { number: "CIT597", teacher="Dr. Dave" }
• You can use new to create a “blank” object, and add fields
to it later:
– var course = new Object();
course.number = "CIT597";
course.teacher = "Dr. Dave";
• You can write and use a constructor:
– function Course(n, t) { // best placed in <head>
this.number = n;
this.teacher = t;
}
– var course = new Course("CIT597", "Dr. Dave"); 27
The document object
• Many attributes of the current document are available via the
document object:

Title Referrer
URL Images
Forms Links
Colors

28
document Methods
• document.write() like a print statement – the output
goes into the HTML document.
• document.writeln() adds a newline after printing.
• document.getElementById() Returns the element that
has the ID attribute with the specified value

document.write("My title is " +


document.title);

29
Example
<HEAD>
<TITLE>JavaScript is Javalicious</TITLE>
</HEAD>
<BODY>
<h3>I am a web page and here is my
name:</h3>
<script type=”text/Javascript”>
document.write(document.title);
</script>
<hr>
30
The navigator Object
• Represents the browser. Read-only!
• Attributes include:
i ne
t e rm is
de e r
appName t o w s
e d
s of b r o
appVersion
n u
t e d
platform of t kin d E)
a e I
wh g us e vs.
e i n ap
b t sc
(Ne
31
navigator Example

if (navigator.appName ==
"Microsoft Internet Explorer") {
document.writeln("<H1>This page
requires Netscape!</H1>");
}

32
The window Object
• Represents the current window.

• There are possible many objects of type Window, the


predefined object window represents the current window.
• Access to, and control of, a number of properties including
position and size.

33
window attributes
• document
• name
• status the status line
• parent

34
some window methods
alert()
close()
prompt()
moveTo() moveBy()
open()
scroll() scrollTo()
resizeBy() resizeTo()

35
The Math Object
• Access to mathematical functions and constants.
• Constants: Math.PI
• Methods:
Math.abs(), Math.sin(), Math.log(), Math.max(),
Math.pow(), Math.random(), Math.sqrt(), …

36
Math object in use
// returns an integer between 1 and 6
function roll() {
var x = Math.random();

// convert to range [0,6.0)


x = x * 6;
// add 1 and convert to int
return parseInt(1+x );
}

document.writeln("Roll is “ + roll() ); 37
Math object in use
<script type ="text/javascript">
<!--
var input1 = window.prompt("Enter first number", "0");
var input2 = window.prompt("Enter second number", "0");
var input3 = window.prompt("Enter third number", "0");
var value1 = parseFloat(input1);
var value2 = parseFloat(input2);
var value3 = parseFloat(input3);
var maxValue = maximum( value1, value2, value3);

document.writeln("First number: " + value1 +


"<br /> Second number: " + value2 +
"<br />Third number: " + value3 +
"<br />Maximum is: " +maxValue );

function maximum(x,y,z)
{
return Math.max(x,Math.max(y,z)); 38
}
//-->
</script>
Array Objects
• Arrays are supported as objects.

• Attribute length

• Methods include:
concat join pop push reverse sort

39
Some similarity to C++
• Array indexes start at 0.
• Syntax for accessing an element is the same:
a[3]++;
blah[i] = i*72;

40
New Stuff (different from C+
+)
• Arrays can grow dynamically – just add new elements at the
end.
• Arrays can have holes, elements that have no value.
• Array elements can be anything
• numbers, strings, or arrays!

41
Four ways to create an array
• You can use an array literal:
var colors = ["red", "green", "blue"];
• You can use new Array() to create an empty array:
– var colors = new Array();
• You can add elements to the array later:
colors[0] = "red"; colors[2] = "blue"; colors[1]="green";
• You can use new Array(n) with a single numeric
argument to create an array of that size
– var colors = new Array(3);
• You can use new Array(…) with two or more arguments
to create an array containing those values:
42
– var colors = new Array("red","green", "blue");
The length of an array
• If myArray is an array, its length is given by
myArray.length
• Array length can be changed by assignment beyond the
current length
• Example: var myArray = new Array(5); myArray[10] = 3;
• Arrays are sparse, that is, space is only allocated for
elements that have been assigned a value
• Example: myArray[50000] = 3; is perfectly OK
• But indices must be between 0 and 232-1
• As in C and Java, there are no two-dimensional arrays; but
you can have an array of arrays: board[3][3]
43
Arrays examples
• car = { myCar: "Saturn", 7: "Mazda" }
– car[7] is the same as car.7
– car.myCar is the same as car["myCar"]
• If you know the name of a property, you can use dot notation:
car.myCar
• If you don’t know the name of a property, but you have it in a
variable (or can compute it), you must use array notation:
car["my" + "Car"]
• var colors = [" blue ",
" green ",
" yellow "];
var x = window.prompt("enter a number "); 44

document.body.style.background = colors[x];
Array of Arrays Example
var board = [ [1,2,3],
[4,5,6],
[7,8,9] ];

for (i=0;i<3;i++)
for (j=0;j<3;j++)
board[i][j]++;

45
Array functions
• If myArray is an array,
– myArray.sort() sorts the array alphabetically
– myArray.sort(function(a, b) { return a - b; }) sorts numerically
– myArray.reverse() reverses the array elements
– myArray.push(…) adds any number of new elements to the end
of the array, and increases the array’s length
– myArray.pop() removes and returns the last element of the array,
and decrements the array’s length
– myArray.toString() returns a string containing the values of the
array elements, separated by commas

46
JavaScript Popup Boxes
• Alert Box
• An alert box is often used if you want to make sure
information comes through to the user.
• When an alert box pops up, the user will have to click
"OK" to proceed.
<script>
alert("Hello World!")
</script>

47
JavaScript Popup Boxes - 2
• Confirm Box
• A confirm box is often used if you want the user to verify or accept
something.
• When a confirm box pops up, the user will have to click either "OK"
or "Cancel" to proceed.
• If the user clicks "OK", the box returns true. If the user clicks
"Cancel", the box returns false.
<script>
function deleteRecord( id){
if(confirm("Are you sure you want to delete this record? ")){
window.location.href = ‘index.php?q=delete' + '&id=' + id;
} 48
}
</script>
JavaScript Popup Boxes - 3
• Prompt Box
• A prompt box is often used if you want the user to input a value
before entering a page.
• When a prompt box pops up, the user will have to click either
"OK" or "Cancel" to proceed after entering an input value.
• If the user clicks "OK“, the box returns the input value. If the user
clicks "Cancel“, the box returns null.

<script>
num1 = window.prompt("Enter the first number");
</script>
49
The End

50

You might also like