You are on page 1of 9

Browser Scripting Introduction

JavaScript

1 2

Client-Server Architecture Client Side Technologies


• JavaScript
• In a client-server architecture, computation is done
- Developed by Netscape, standardized by ECMA
either in the client or in the server
- Supported by all browsers (although not all support the standard)
• There are cases where we can choose whether to
• VBScript
perform the computation in the client or in the server
- Developed by Microsoft
- For example, validating forms - Supported only by Microsoft Internet Explorer
• There are cases where we cannot choose where to - A light version of Microsoft Visual Basic
perform the computation • Java Applets
- For example, accessing a database - Developed by Sun
3 4

About Applets

• An applet is a Java class that runs in a frame that is


embedded in a Web page
<object type="application/x-java-applet"
classid="myApplet.class" width="x" height="y">

• When a browser loads the Web page, the applet byte-


code (.class file) is downloaded to the client box and
executed by the browser
• Commonly used for games, graphics, etc.
5 6

1
Browser Scripting Web Architecture for Scripts

Client Server
• Browser scripts are procedural programs
Web browser
embedded inside HTML Web
(HTTP)
HTML Page: HTML/HTTP HTML/HTTP
Server
<script type="text/javascript">script</script> <SCRIPT>
…code..…
TCP/IP
Internet
TCP/IP
</SCRIPT>
<script type="text/vbscript">script</script>
• Can read and manipulate HTML elements, CSS
properties, and the browser itself built-in
Script HTML
interpreter pages with
embedded
script
7

Why are Scripts Needed? JavaScript History

• Generating HTML content dynamically • Introduced in Netscape 2 (1996)


• Monitoring and responding to user events • Standardized by ECMA under the name
• Validating forms before submission ECMAScript (1997-1999)

• Manipulating HTTP cookies • The latest version is ECMAScript 3, and it is

• Interaction among the frames and windows of the equivalent to JavaScript 1.5

browser

9 10

JavaScript is NOT Java!

• JavaScript is not compiled


• JavaScript is typically executed by Web browsers
JavaScript Basics and not as stand-alone applications
• JavaScript and Java have some similarity in
syntax
• The choice of the name is mainly for historical
reasons
11 12

2
Dynamic HTML Content:
Example 1
<html>
<head><title>JS Example</title></head> <body>
<h2>Before the script</h2>
<script type="text/javascript">
document.write('<h1>In the script<\/h1>')
</script>
<h2>After the script</h2>
</body></html>
13 14

Dynamic HTML Content: Dynamic HTML Content:


Example 2 Example 3
<html> <h2>Hello and
<head><title>JS Example</title></head><body> <i><script type="text/javascript">
<h2>Before the script</h2><h1> hours = new Date().getHours();
<script type="text/javascript"> if (hours < 10) { document.write("good morning") }
document.write(new Date().toLocaleString()) else {document.write("good day") }
</script> </script></i>.
</h1><h2>After the script</h2> </h2>
</body></html>
15 16

Basic Constructs Variables


• Statement blocks var x=5, y=7; • JavaScript variables are not typed! (but values are)
var x=5 document.write(x+y);
document.write(x); - var x = 5; x="abcd";...
- Semicolon (;) is optional at end of line • Thus, the value of a variable is characterized by
both value and type
• Conditions: if, if-else, ?:, switch
if (condition) {statements if true} • Variables are declared with var keyword:
else {statements if false} x= (y>0)? y:0
- var x; var y=5;

• A variable name consists of letters, digits, and


• Loops: for, while, do-while
underscores (_), and does not begin with a digit
while (condition) {statements}
17 18

3
Data Types Some of the Reserved Words

• Values have one the following types: abstract do public if typeof


as in return implements use
- number: 5, 2.3, 0xFF, 6.67e-11 break instanceof else import var
- object: new Date() case interface export static void
• Arrays: [1,"ab ba",17.234] catch is extends super while
• null class namespace false switch with
const new final this
- string: "Hello World"
continue null finally throw
- boolean: true, false default package for true
You can use typeof(x)
- undefined: no value assigned... to get the type of x: delete private function try
number, string, object... 19 20

Operators Types of Equality

• Arithmetic: + ++ - -- * / % • The equals == checks if both operands are equal


• Comparison: == != === !== > >= < <= after performing type conversion

• Logical: & && | || ! • The equals === checks if both operands are of

• Bitwise: & | ^ ~ << >> >>> the same type and equal

• String: + • Example:
- Is 34 == "34" ? Is 34 == "3"+"4" ?
• Assignments: = += -= *= /= <<= |= ...
- Is 34 === "3"+"4" ? Is 34 !== "3"+"4" ?
21 22

An Example

<script type="text/javascript">

for (var counter = 1 ; counter <= 8 ; ++counter) {

var fontsize = counter + 10; fontsize+="pt";

document.write("<p style='font-size: "+fontsize+"'>"


+ "Font size " + fontsize + " <\/p>");
}

</script>

23 24

4
Functions

• JavaScript functions are special objects with operator ()


• Syntax: function fname(args...) {statements}
Functions • Usually, functions are defined at the head of the file
- Why?
• Some functions are predefined
- For example, parseInt(string)

• Functions can return values

25 26

Function Example Function Values


<html>
<head> • Numbers and Booleans are passed to functions
<script type="text/javascript">
function add(x,y) { by value
return x+y;
}
</script> • Objects and strings are passed to functions by
</head>
reference
<body> <h1>
<script type="text/javascript"> • Numbers and Boolean values are always returned
sum = add(4,5);
document.write("4+5="+sum); by value
</script>
</h1> </body> • Objects and strings are returned by reference
</html> 27 28

Undeclared Arguments An Example

• Function may receive arguments without declaring them What is the result of the following code?
• Within a function, its arguments are held in the function myConcat(separator) {
var result="";
arguments array // iterate through arguments
for (var i=1; i<arguments.length; i++) {
- can be accessed with arguments[i] result += arguments[i] + separator;
}
- The number of arguments is arguments.length return result;
• Hence, it is possible to define functions that take any }

number of arguments con = myConcat(", ","red","orange","blue");

29 30

5
Predefined Functions Variable Scopes

• JavaScript include several predefined functions • JavaScript variables are recognized inside their
• For example, declaration scope
- eval(code-string) – gets a string of JavaScript code, • Hence, global variables should be declared
evaluates it and executes it outside the functions
• It allows dynamic code execution
• A variable declared in a function can also be
- parseInt(string) – takes a string argument and global, if var is omitted
converts its beginning to an integer (or return NaN)
- However, avoid this bad style...
31 32

Object Model

• JavaScript objects are similar to associative arrays


• That is, an object associates identifiers (e.g., firstName)
Objects and Arrays with values (attributes) (e.g., "John")
• Those values may be other objects (nested objects)
• Those values can also be functions (methods)
- e.g., function setPersonAge(age) {this.age = age}

• When o.f() is invoked, o can be referred to as this

33 34

Creating Objects Creating Objects (cont)

• Objects can be created in several ways: • Object Constructors


• Object initializers - define a constructor function
var theNissan = - create the new object using new
{make:"Nissan", year:2003, color:"blue"}
function car(make,year,color) {
this.make = make
• Object assignments this.year = year
this.color = color
theMazda = { make:"Nissan" } }
theMazda.year = 2002;
theMazda.color="black"; theHonda = new car("Honda", 2001, "green")
35 36

6
Defining Methods Defining Methods (cont)

• Methods are associated with objects just like attributes theNissan = {make:"Nissan", year:2003, color:"blue"}
function niceString() { theNissan.str = niceString;
return "<span style='color:"+ this.color + "'>" +
this.make + " "+ this.year + "<\/span>" function car(make,year,color) {
} this.make = make
this.year = year
this.color = color
theNissan = this.str = niceString
{make:"Nissan",year:2003,color:"blue",str:niceString} }

theHonda = new car("Honda", 2001, "green")

37 38

Accessing Object Properties The Complete Example


function niceString() {
• Object attributes can be accessed in several ways: return "<span style='color:"+ this.color + "'>" +
this.make + " "+ this.year + "<\/span>"
- object.attName }

- object["attName"] function car(make,year,color) {


• Thus, object methods are invoked in Java/C++ style: this.make = make; this.year = year;
this.color = color; this.str = niceString
- object.method(arguments) }
• Alternatively:
var theHonda = new car("Honda", 2001, "green");
- object["method"](arguments)
document.write(theHonda.str());
39 40

Array Objects Creating Arrays

• Arrays are supported as objects • var a = ["red", "blue", "green"]


- Allocates an array of 3 cells and initializes the values
• Attribute length
• var b = new Array(5)
• Methods include:
- Allocates an array of 5 cells without initializing
concat, join, pop, push, reverse, sort, shift, ... values
• Arrays can be passed to functions as arguments • var c = new Array()

• The array is passed by-reference - Creates a new empty array

41 42

7
Array Elements

• Array elements need not have the same type


- arr1 = ["hello", 1, true]
• Java-like access: arr[i]
Miscellaneous
• Array indices need not be contiguous
- arr1[10] = 66
• Multi-dimensional arrays are arrays of arrays
- var matrix = [ [0, 1, 1], [1, 1, 0], [0, 0, 0]]
43 44

JavaScript and XHTML Strict Wrapping Code in CDATA

• Embedding JavaScript code inside XHTML may violate


<script type="text/javascript"/>
XML rules
//<![CDATA[
- e.g., x<5 && x>2
regular JavaScript code
• One solution is to import JavaScript code from external
...
files, e.g.: <script type="..." src="jsfile.js"/>
//]]>
- Always a good habit... </script>
• Another solution: wrap the code in an XML CDATA
section
45 46

The String Object String Common Methods


• charAt (index) • split(string)
• JavaScript has a built-in String object
• charCodeAt(index) • substr(start, length)
- not the primitive string! • substring(start, end)
• concat(string)
• Create a String object from a string primitive: • fromCharCode(value1, value2, …) • toLowerCase()

- myString = new String("This is a string object") • toUpperCase()


• indexOf(substring, index)
• valueOf()
• Extract the primitive string from a String object: • lastIndexOf(substring, index)
• match(regexp)
- str = myString.valueOf() • slice(start, end)

47 48

8
An Example - Format Verification The Math Object

• What does the following function do? • The object Math is used for mathematical operations
function getString() { - E.g., Math.pow(x,2)
var result = null;
while(result==null) { • Other useful functions:
var answer = prompt("Your first name:") • abs(x) • cos(x) • pow(x, y)
if(answer!=null) {
• round(x) • sin(x) • sqrt(x)
result = new String(answer);
result = result.toLowerCase().match("^[a-z]+$"); • ceil(x) • tan(x) • log(x)
} • floor(x) • exp(x) • max(x, y)
if(result==null) { alert("Don't mess with me!") }
• min(x, y)
}
return answer } 49 • Math Also includes constants such as: Math.E, Math.PI 50

The with Statement The Date Object

• Establishes the default object for a set of • Create the current date: new Date()
statements • Create an arbitrary date: new Date(date-string)
• Within the set of statements, any property • Common methods of Date:
references that do not specify an object are • getDate() • getHours()
assumed to be of the default object • getFullYear() • getMinutes()
var a, x, y • getMonth() • getSeconds()
var r=10
• getDay • getMilliseconds()
with (Math) {
a = PI * r * r; x = r * cos(PI); y = r * sin(PI/2) } 51
• getTime() • toLocaleString() 52

You might also like