Client-Side Programming JavaScript Dr. Ahmed Youssef.

100
Client-Side Programming JavaScript Dr. Ahmed Youssef

Transcript of Client-Side Programming JavaScript Dr. Ahmed Youssef.

Client-Side ProgrammingJavaScript

Dr. Ahmed Youssef

Introduction

JavaScript is used in web pages for:• Dynamics: mouse clicks, pop up windows, and

animations• Client-side execution: validating input, processing

requests It avoids Client/Server communication and traffic JavaScript is executed on client-side JavaScript is simple, powerful, and interpretive

language and requires only a web browser

2Ahmed Youssef: SWE444: Internet and Web Application Development

Web Pages Layers

Web pages have 3 layers…

1. Structural/Content Layer (XHTML)

2. Presentational Layer (CSS)

•How things look

3. Behavioral Layer (JavaScript and DOM)

•How websites behave

3Ahmed Youssef: SWE444: Internet and Web Application Development

JavaScript and Java

JavaScript supports most Java expressions and basic control structure

JavaScript - programs are interpreted in the browser

Java - programs are compiled and can be run as stand alone applications

4Ahmed Youssef: SWE444: Internet and Web Application Development

What is a script

A program or sequence of instructions that is interpreted or carried out by another program 

A program embedded in an HTML document

Scripts + HTML DHTML (dynamic HTML)

5Ahmed Youssef: SWE444: Internet and Web Application Development

What is JavaScript?

Created by Netscape • Originally called LiveWire then LiveScript

A client-side scripting language

• Client-side refers to the fact that it is executed in

the client (browser) that the viewer is using.

• A server-side language is one that runs on the Web

server. Examples: PHP, ASP

6Ahmed Youssef: SWE444: Internet and Web Application Development

What can it be used for

Text animation graphic animation HTML forms submission client-side forms data validation web site navigation

Client-side Languages

User-agent (web browser) requests a web page

http request

http response

• Web page (with JavaScript) is sent to PC

• JavaScript is executed on PC

• Can affect the Browser and the page itself

• JavaScript is executed on PC

• Can affect the Browser and the page itself

8Ahmed Youssef: SWE444: Internet and Web Application Development

Client-Side Programming

9Ahmed Youssef: SWE444: Internet and Web Application Development

Client-side

Validating Form information, • i.e., making sure all the fields are complete before

submitting data back to the serverModifying a web page based on Mouse

Events.•Can turn a web page into a user interface with

interactive buttons and controls

10Ahmed Youssef: SWE444: Internet and Web Application Development

Server-side Languages

User-agent (web browser) requests a web page

http request

• Server detects PHP code in page, executes the code, and sends the output to the user

http response

• Web page (with PHP Output) sent to PC

• User never sees the PHP, only the output

• Cannot affect the browser or client PC

11Ahmed Youssef: SWE444: Internet and Web Application Development

Server-Side Programming

12Ahmed Youssef: SWE444: Internet and Web Application Development

Server-side Programming

• CGI• PHP• ASP• Java Servlet, …

Web ClientWeb Server

Internet

Client-side Programming

• XHTML• Javascript• Dreamweaver• Flash• XML …

Database

Server side and Client side Programming

13Ahmed Youssef: SWE444: Internet and Web Application Development

ServerBrowser

Request

ReplyFile

System

Static Web Model

14Ahmed Youssef: SWE444: Internet and Web Application Development

ServerBrowserRequest

ReplyFile

System

Dynamic Web Model

OtherPrograms

15Ahmed Youssef: SWE444: Internet and Web Application Development

Placement of JavaScripts

JavaScript can be put in the <head> or in the <body> of an HTML document• <script> tag is used to embed JavaScript code in

HTML code of a web page• In-line code in various tags throughout the

document JavaScript can be put in a separate .js file

• <script src="JavaScriptFile.js"></script>• An external .js file lets you use the same

JavaScript on multiple HTML pages

16Ahmed Youssef: SWE444: Internet and Web Application Development

17

The <script>…</script> tag

The code for the script is contained in the <script>…</script> tag

<script type="text/javascript">

.

.

.

</script>

Displaying text

The document.write() method writes a string of text to the browser

<script type="text/javascript">

document.write("<h1>Hello, world!</h1>");

</script>

18Ahmed Youssef: SWE444: Internet and Web Application Development

document.write()

document.write("<h1>Hello,world!</h1>");

Enclosed in quotes -- denotes a "string"

Ends in a semicolon

19Ahmed Youssef: SWE444: Internet and Web Application Development

20

Getting User Input

Use the prompt() function• Will display a pop-up window asking the user to

enter data Examples:

name = prompt("What is your name?");payRate = prompt("Enter your pay rate: ");score = prompt("Please enter the score: ");

Comments in JavaScript

Two types of comments• Single line

• Uses two forward slashes (i.e. //)

• Multiple line• Uses /* and */

21Ahmed Youssef: SWE444: Internet and Web Application Development

Single Line Comment Example

<script type="text/javascript">

// This is my JavaScript comment

document.write("<h1>Hello!</h1>");

</script>

22Ahmed Youssef: SWE444: Internet and Web Application Development

Multiple Line Comment Example

<script type="text/javascript"> /* This is a multiple line comment. * The star at the beginning of this line is optional. * So is the star at the beginning of this line. */ document.write("<h1>Hello!</h1>"); </script>

23Ahmed Youssef: SWE444: Internet and Web Application Development

Find the Bug!

<script type="text/javascript">

/* This is my JavaScript comment

* that spans more than 1 line.

*

document.write("<h1>Hello!</h1>");

</script>

24Ahmed Youssef: SWE444: Internet and Web Application Development

JavaScript Statements

<html><head><title>My Page</title></head><body><script language="JavaScript">

document.write('This is my firstJavaScript Page');

</script></body></html>

25Ahmed Youssef: SWE444: Internet and Web Application Development

JavaScript Statements

<html><head><title>My Page</title></head><body><script language= "JavaScript">

document.write('<h1>This is my firstJavaScript Page</h1>');

</script></body></html>

HTML writteninside JavaScript

26Ahmed Youssef: SWE444: Internet and Web Application Development

JavaScript Statements

<html><head><title>My Page</title></head><body><p><a href="myfile.html"onMouseover="window.alert('Hello');"> My Page</a></p></body></html> JavaScript written

inside HTMLAn Event

27Ahmed Youssef: SWE444: Internet and Web Application Development

Example Statements

<script language="JavaScript">window.prompt('Enter your name:','');</script><form><input type="button" Value="Press"

onClick="window.alert('Hello');"></form>

Note quotes: " and '

28Ahmed Youssef: SWE444: Internet and Web Application Development

Input and Output

The input functions available are:• prompt (message, defaultvalue) takes an

input and returns it to the JavaScript program• confirm (question) asks the user to confirm

an input value and return a Boolean value The output functions available are:

• document.write (string)• alert (string)

Ahmed Youssef: SWE444: Internet and Web Application Development 29

HTML Forms and JavaScript

JavaScript is very good at processing user input in the web browser

HTML <form> elements receive input

<form action="…" method="…" name="…" … > any number of form elements and plain HTML </form>

HTML Form Elements<input type="text"/>

<input type="password"/>

<input type="button" value="Label"/>

<input type="submit"/>

<input type="reset"/>

<input type="image" src="smiley.jpg"/>

<input type="checkbox"/>

<input type="radio" name="sex" value="Male"/>

<input type="radio" name="sex" value="Female"/><textarea rows="3" cols="40">This is the initial textspread over two lines</textarea><select> <option>First</option> <option>Second</option></select><input type="file"/>

Naming Form Elements in HTML

<form name="addressform">Name: <input name="yourname"><br />Phone: <input name="phone"><br />Email: <input name="email"><br /></form>

32Ahmed Youssef: SWE444: Internet and Web Application Development

Forms and JavaScript

document.formname.elementname.value

document.addressform.yourname.value

document.addressform.phone.value

document.addressform.email.value

33Ahmed Youssef: SWE444: Internet and Web Application Development

Using Form Data

Personalising an alert box

<form name="alertform">

Enter your name:

<input type="text" name="yourname">

<input type="button" value= "Go" onClick="window.alert('Hello ' + document.alertform.yourname.value);">

</form>

34Ahmed Youssef: SWE444: Internet and Web Application Development

<html> <body><form> <input type=button name=btn1 value="Click A"

onClick="alert('button A was clicked');" > <input type=button name=btn2 value="Click B"

onClick="alert('button B was clicked');" > </form> </body> </html>

Ahmed Youssef: SWE444: Internet and Web Application Development35

Variables and Arithmetic Operators in JavaScript

36

37

Reserved Words (Keywords) in JavaScript

abstract delete function null throw

boolean do goto package throws

break double if private transient

byte else implements

protected true

case enum import public try

catch export in return typeof

char extends instanceof short var

class false int static void

const final interface super volatile

continue finally long switch while

debugger float native synchronized with

default for new this

Variables

Variables names must begin with a letter or underscore

Variable names are case-sensitive Variables are untyped (they can hold values

of any type) The word var is optional (but it’s good style to

use it)

39

Which Are Legal Identifiers?

AREA 3D lucky*** num45 Last-Chance #values x_yt3 pi num+ %done area_under_the_curve

40

Declaring Variables

Before using a variable, you need to declare it.

The declaration statement includes the var keyword and the name of the variable.

Examples of variable declarations:

var ball; var ball, area;var area;

41

More About Variables

In JavaScript variables can hold four basic types of values• Numbers

• i.e. 40, 15.5, 700

• Strings• i.e. "Hello, World!", "Linux is cool!"

• Booleans• i.e. true, false

• Null• i.e. null

42

Using Variables: Initialization

Variables may be be given initial values, or initialized, when declared. Examples:

var length = 7;

var diameter = 5.9;

var message = "Hello!";

var walletEmpty = true;

7

5.9

“Hello!”

length

diameter

message

truewalletEmpty

43

Using Variables: Assignment

Uses the assignment operator =

Examples:

diameter = 5.9 ; area = length * width ;

JavaScript Arithmetic Operators

Ahmed Youssef: SWE444: Internet and Web Application Development 44

Operator Description Example Result

+ Addition x=y+2 x=7 y=5- Subtraction x=y-2 x=3 y=5* Multiplication x=y*2 x=10 y=5/ Division x=y/2 x=2.5 y=5

% Modulus (division remainder)

x=y%2 x=1 y=5

++ Increment x=++y x=6 y=6x=y++ x=5 y=6

-- Decrement x=--y x=4 y=4x=y-- x=5 y=4

Given that y=5, the table below explains the arithmetic operators:

JavaScript Assignment Operators

Ahmed Youssef: SWE444: Internet and Web Application Development 45

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

Given that x=10 and y=5, the table below explains the assignment operators:

Adding Strings and Numbers

x=5+5;document.write(x);x="5"+"5";document.write(x);x=5+"5";document.write(x);x="5"+5;document.write(x);

Ahmed Youssef: SWE444: Internet and Web Application Development 46

10

55

55

55

Comparison Operators

Ahmed Youssef: SWE444: Internet and Web Application Development 47

Operator Description Example

== is equal to x==8 is false

=== is exactly equal to (value and 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<8 is true

>= is greater than or equal to x>=8 is false

<= is less than or equal to x<=8 is true

Conditional Statements

if statement  if...else statement  if...else if....else statement  switch statement 

Ahmed Youssef: SWE444: Internet and Web Application Development 48

Example

var d = new Date();var time = d.getHours();if (time < 10)  {  document.write("Good morning!");  }else  {

  document.write("Good day!");  }

Ahmed Youssef: SWE444: Internet and Web Application Development 49

50

Gotcha! = versus ==var a = 2;if(a = 1) /* semantic (logic) error! */{ alert("a is one");}else if(a == 2){ alert("a is two");}else{ alert("a is " + a);}

51

Multiple Selection with if

if (day == 0 ) { alert ("Sunday") ;}if (day == 1 ) { alert ("Monday") ;}if (day == 2) { alert ("Tuesday") ;}if (day == 3) { alert ("Wednesday") ;}

52

Multiple Selection with if-elseif (day == 0 ) { alert ("Sunday") ;} else if (day == 1 ) { alert ("Monday") ;} else if (day == 2) { alert ("Tuesday") ;} else if (day == 3) { alert ("Wednesday") ;} else if (day == 4) { alert ("Thursday") ;}

else if (day == 5) { alert ("Friday") ;} else if (day == 6) { alert ("Saturday") ;} else { alert ("Error - invalid day.") ;}

53

switch Exampleswitch ( day ){

case 0: alert ("Sunday") ; break ;case 1: alert ("Monday") ; break ;case 2: alert ("Tuesday") ; break ;case 3: alert ("Wednesday") ; break ;

case 4: alert ("Thursday") ; break ;case 5: alert ("Friday") ; break ;case 6: alert ("Saturday") ; break ;default: alert ("Error -- invalid day.") ;

}

JavaScript Functions

How to Define a Function

function functionname(var1,var2,...,varX){

some code}

Ahmed Youssef: SWE444: Internet and Web Application Development 54

55

Sample Function Call

alert is the name of a predefined

function in the JavaScript language

alert("Hello World!"); this statement is

is known as a

function call

this is a string we are passing

as an argument (parameter) to

the alert function

56

Sample Programmer-Defined Function

<head><script type="text/javascript"> function PrintMessage() { alert("A message for you:\n\nHave a nice day!"); }</script> </head><body> <script type="text/javascript">

PrintMessage();</script></body>

Function

Definition

Function Call

57

Screenshot of Function Example

The return Statement

<head>

<script type="text/javascript">function product(a,b){ return a*b; }

</script> </head>

<body><script type="text/javascript">document.write(product(4,3));

</script> </body>

Ahmed Youssef: SWE444: Internet and Web Application Development 58

Example

<html> <head>

<script type="text/javascript">

function myFunction()

{ return ("Hello world!"); }

</script> </head>

<body>

<script type="text/javascript">

document.write(myFunction())

</script> </body> </html>

Ahmed Youssef: SWE444: Internet and Web Application Development 59

JavaScript Loops

<html> <body><script type="text/javascript">var i=0;for (i=0;i<=5;i++){

document.write("The number is " + i);

document.write("<br />");}

</script> </body> </html>

Ahmed Youssef: SWE444: Internet and Web Application Development 60

Another Examplehtml>

<head> <title>computing factorials</title></head>

<body>

<h1>Looping example of javascript</h1>

<script language="javascript">

document.write("<h1>factorial table</h1>");

for ( i = 1, fact = 1; i < 10; i++) {

fact = fact * I;

document.write(i + "! = "+ fact);

document.write("<br>");

}

</script> </body> </html>61

Another Example

62

JavaScript Loops

<html> <body><script type="text/javascript">var i=0;while (i<=5)  {

  document.write("The number is " + i);  document.write("<br />");  i++;

  }</script> </body> </html>

Ahmed Youssef: SWE444: Internet and Web Application Development 63

JavaScript Loops

<html> <body> <script type="text/javascript">var i=0;do  {  document.write("The number is " + i);

  document.write("<br />");  i++;

  }while (i<=5);</script> </body> </html>

Ahmed Youssef: SWE444: Internet and Web Application Development 64

for...in Statement

for...in statement loops through the properties of an object.

Syntax

for (variable in object)

{

  code to be executed

}

Ahmed Youssef: SWE444: Internet and Web Application Development 65

JavaScript Loops

Looping through the properties of an object:

Example

var person = { fname: "John", lname: "Doe " , age:25 }; for (x in person){ document.write(person[x] + " ");}

Ahmed Youssef: SWE444: Internet and Web Application Development 66

67

Event Handlers

Special-purpose functions that come predefined with JavaScript

They are mostly called from the HTML part of a Web page and not the <script> …

</script> part

68

69

<input type=“submit” name=“sendEmail” value=“Send eMail” onMouseOver= “if (document.sendEmail.sender.value.length < 1) window.alert(‘Empty From field! Please correct’)”>

70

JavaScript Event Handling

The event handler attribute consists of 3 parts:• The identifier of the event handler• The equal sign• A string consisting of JavaScript statements

enclosed in double or single quotes

71

onMouseOver=“checkForm( )”

JavaScript that goes between the <script>, </script> tags:

JavaScript included as an attribute of the “Send eMail” button:

function checkForm() {

if ( document.sendEmail.sender.value.length < 1) { window.alert( “Empty From field! Please correct” ); }}

72

73

onClick=“vuWindow”()

JavaScript that goes between the <SCRIPT>, </SCRIPT> tags:

JavaScript included as an attribute of the “New Window” button:

function vuWindow() { window.open(“http://www.vu.edu.pk/”) ;}

Client-Side ProgrammingJavaScript

Dr. Ahmed Youssef

75

Event Categories

Keyboard and mouse events• onClick

Load events• The page first appears on the screen: onLoad

Form-related events• onFocus()

Others• Errors, window resizing.

76

Events defined by JavaScriptHTML

elementsHTML tags

JavaScript defined events

Description

Link <a> clickdblClick

mouseDownmouseUp

mouseOver

Mouse is clicked on a linkMouse is double-clicked on a linkMouse button is pressedMouse button is releasedMouse is moved over a link

Image <img> loadaborterror

Image is loaded into a browserImage loading is abandonedAn error occurs during the image loading

Area <area>

mouseOvermouseOutdblClick

The mouse is moved over an image map areaThe mouse is moved from image map to outsideThe mouse is double-clicked on an image map

Form <form>

submitReset

The user submits a formThe user refreshes a form

… … … …

77

A Few of Event Handlers

onClickonDblClickonMouseOveronMouseDownonFocus

onBluronResetonSubmitonLoadonUnload

Event HandlersEvent Handlers Triggered when

onChange The value of the text field, textarea, or a drop down list is modified

onClick A link, an image or a form element is clicked once

onDblClick The element is double-clicked

onMouseDown The user presses the mouse button

onLoad A document or an image is loaded

onSubmit A user submits a form

onReset The form is reset

onUnLoad The user closes a document or a frame

onResize A form is resized by the user

79

onLoad event Handler

<html><head><title>onLoad and onUnload Event Handler Example</title></head><body onLoad=”alert(‘Welcome User’)” onUnload=”alert(‘Thanks for visiting the page’)”>Load and UnLoad event test.</body></html>

INE2720 – Web Application Software Development All copyright

s reserved by C.C. Cheung 2003.

80

User Events, Form Example<html><head> <script language=“JavaScript">function dontClick() { alert("I told you not to click!");}</head><body><h1>Simple JavaScript Button</h1><form> <input type=“button" value="Don't Click Me" onClick="dontClick()"></form> </body></html>

81

onMouseOver and onMouseOut Event Handlers

<html><body><a href=“http://www.uoh.edu.sa” onMouseOver = “alert(‘Now mouse is over the

link’) “onMouseOut = “alert (‘Mouse has moved out’)”>A Link Page </a></body> </html>

82

onFocus & onBlur

onFocus executes the specified JavaScript code when a window receives focus or when a form element receives input focus

onBlur executes the specified JavaScript code when input focus leaves the field of a text, textarea, or a select option.

83

84

<input type="text" name="age"onBlur="checkAge( ) ">

JavaScript that goes between the <script>, </script> tags:

JavaScript included as an attribute of the input tag:

function checkAge( ) {

if( parseInt( document.form1.age.value ) < 12 ) {

window.alert( "Stop! You are younger than 12" ) ;

}

}

85

<html> <head> <script>function checkage() {

if( document.form1.age.value < 12) window.alert("stop! you are younger than 12" ) ;

}</script></head><body ><form name="form1" > <table border="1"> <tr> <td>age</td> <td><input type="text" name="age" onblur="checkage() "></td></tr> <tr> <td>phone number</td> <td><input type="text" name="phno"></td> </tr><tr> <td><input type="reset" value="reset"></td> <td><input type="submit" value="submit"></td></tr> </table></form></body></html>

Example

<html><head>

<script language="javascript">

function valid( )

{

var input=document.myform.data.value;

if (input<0) {

alert("please enter a value that is greater than 0");

}

}

</script> </head>

Ahmed Youssef: SWE444: Internet and Web Application Development 86

<body> <h3>example of onblur event handler:</h3>

try entering a value less than zero:<br>

<form name="myform">

<input type="text" name="data" value="" size="10" onblur='valid( )'>

</form>

</body>

</html>

Ahmed Youssef: SWE444: Internet and Web Application Development 87

onClick

a JavaScript function is called when an object in • a button (regular, radio, reset and submit) is

clicked, • a link is pushed, • a checkbox is checked

Ahmed Youssef: SWE444: Internet and Web Application Development 88

<form name=myform onSubmit="alert(document.myform.rbtn[index].value)"> <br>

<input type=radio name=rbtn value="North" onClick="index=0" >North <br>

<input type=radio name=rbtn value="East" onClick="index=1" >East <br>

<input type=radio name=rbtn value="South" onClick="index=2" >South <br>

<input type=radio name=rbtn value="West" onClick="index=3" >West <br><input type=submit>

</form>

90

Document Object Model (DOM)

DOM is an object-oriented model that describes how all elements in an HTML page are arranged.

It is used to locate any object in your HTML page (an unique address).

91

How the DOM works?

<head><script>function toggle() { document.img.button1.src=“button_on.gif”; }</script></head><body><a href=“test.html” onmouseover=“toggle()”> <img name=“button1” src=“button_off.gif”></a></body>

actionreaction

Action Event JavaScript DOM Reaction

src=“button_off.gif” onmouseover toggle() document.img.button1 Src=“button_on.gif”

1) User moves mouse over object2) Event senses that something happened to the object3) JavaScript tells the object what to do (Even handler)4) Locates object on the web page5) Object’s image source is changed

92

Object Hierarchy

window

document frame location history

anchor image form link

button checkbox

select

textarea

submit

radio

reset

text

93

The “window” Object

It is the default object and is created automatically when a page is loaded.

Since it is the default object, we may omit writing window explicitly.• document.write(“a test message”);• window.document.write(“a test message”);

94

The “document” Object

The document object represents a web document or a page in a browser window.

95

Properties and methods of the “document” Object

Property Description

bgColor A string value representing the background color of a document

alinkColor

A string value representing the color for active links

location A string value representing the current URL

title A string value representing the text specified by <title> tag

Method Description

clear() Clears the document window

write(content) Writes the text of content to a document

writeln() Writes the text and followed by a carriage return

open() Open a document to receive data from a write() stream

close() Closes a write() stream

96

The “history” Object

Each time you visit a web page and click on the “Back” or “Forward” arrow buttons on your browser toolbar, you are accessing the history list.

97

Properties and methods of the “history” Object

Property Description

length An integer value representing the number of links in the history object

current Contains the URL of the current page

next Contains the URL of the next entry in the history list

previous Contains the URL of the previous entry in the history list

Method Description

back() Sends the user to the previous page in the history list

forward() Sends the user to the next page in the history list

go(x) Sends back or forward by “x” number of pages in the history list

98

The “form” Object

HTML forms can include eight types of input elements• Text fields, Textarea fields• Radio buttons• Check box buttons• Hidden fields• Password fields• Combo box select menu• List select menu

99

Form Validation Script

<html><head><title>Form Example</title><script LANGUAGE="JavaScript">function validate() { if (document.form1.yourname.value.length < 1) { alert("Please enter your full name."); return false; } if (document.form1.address.value.length < 3) { alert("Please enter your address."); return false; } if (document.form1.phone.value.length < 3) { alert("Please enter your phone number."); return false; } return true;}</script></head>

<body><h1>Form Example</h1><p>Enter the following information. When you press the Display button, the data you entered will be validated, then sent by email.</p>

<form name="form1" action="mailto:[email protected]" enctype="text/plain“ onSubmit="validate();">

<p><b>Name:</b> <input type=“text" length="20" name="yourname"></p><p><b>Address:</b> <input type=“text" length="30" name="address"></p><p><b>Phone: </b> <input type=“text" length="15" name="phone"></p><p><input type=“submit" value="Submit"></p>

</form></body></html>

Objects

window - the current browser window window.history - the Netscape history list window.document - the html document currently in

the browser client area window.location - the browser location field window.toolbar - the browser toolbar window.document.link - an array containing all of the

links in the document window.document.anchor - an array of all the anchor

points in the document