swe 444 internet and web application development( javascript )

Post on 16-Mar-2016

33 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

DESCRIPTION

SWE 444 Internet and Web Application Development( javaScript ). Mr.Abdullah Mrian. Overview A "scripting" language for HTML pages - a scripting language is a lightweight programming language. Embed code in HTML pages so they are downloaded directly to browser. - PowerPoint PPT Presentation

TRANSCRIPT

SWE 444Internet and Web Application

Development(javaScript)

Mr.Abdullah Mrian

Overview

A "scripting" language for HTML pages - a scriptinglanguage is a lightweight programming language.

Embed code in HTML pages so they are downloadeddirectly to browser.

The browser interprets and executes the script (it is not compiled).

Was designed to add interactivity to HTML pages.

Everyone can use JavaScript without purchasing a license.

Supported by all major browsers.

…Overview

Do not declare data types for variables.

Scripts can manipulate "browser objects:"HTML form elementsImagesFramesetc.

For security – cannot write to disk (when run on a client)

Abilities

Generating HTML content dynamically.

Monitoring and responding to user events.

Validate forms before submission.

Manipulate HTTP cookies.

Interact with the frames and windows of the browser.

Customize pages to suit users.

It is not Java

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 is seldom used to write complete “programs”.Instead, small bits of JavaScript are used to add functionality to HTML pages.JavaScript is often used in conjunction with HTML “forms”.

….It is not Java

JavaScript has some features that resemble features in Java:JavaScript has Objects and primitive data types.JavaScript has qualified names; for example: document.write("Hello World");JavaScript has Events and event handlers.Exception handling in JavaScript is almost the same as in Java.

JavaScript has some features unlike anything in Java:Variable names are untyped: the type of a variable depends on the value it is currently holding.Objects and arrays are defined in quite a different way.JavaScript has with statements and a new kind of for statement.

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).

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.

Dynamic HTML …

Web Architecture for JavaScript

Client and Server

JavaScript can be used:On the client sideOn the server

More lightweight and reliable on clients than Java (Applets).

Useful for developing interactive interface (Dynamic HTML).

Example

JavaScript code is included within <script> tags:

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.

Dealing with old browsers

Some old browsers do not recognize script tags:These browsers will ignore the script tags but will display the included JavaScript.To get old browsers to ignore the whole thing, use:

The <!-- introduces an HTML comment.

To get JavaScript to ignore the HTML close comment, -->, the // starts a JavaScript comment, which extends to the end of the line.

Where to put JavaScript

The <script>…</script> tagThe 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>

document.write()

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

Enclosed in quotes -- denotes a "string"

Ends in a semicolon

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 */

Single Line Comment Example

<script type="text/javascript"> // This is my JavaScript comment document.write("<h1>Hello!</h1>"); </script>

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>

Find the Bug!

<script type="text/javascript"> /* This is my JavaScript comment * that spans more than 1 line. * document.write("<h1>Hello!</h1>"); </script>

JavaScript Statements

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

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

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

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 written

inside JavaScript

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 writteninside HTML

An Event

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 '

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)

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>

Forms and JavaScriptdocument.formname.elementname.value

document.addressform.yourname.valuedocument.addressform.phone.valuedocument.addressform.email.value

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>

<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>

34

Reserved Words (Keywords) in JavaScript

abstract delete function null throwboolean do goto package throwsbreak double if private transientbyte else implement

sprotected true

case enum import public trycatch export in return typeofchar extends instanceof short varclass false int static voidconst final interface super volatilecontinue finally long switch whiledebugger float native synchronized withdefault 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)

Which Are Legal Identifiers?

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

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;

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

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

Using Variables: Assignment

• Uses the assignment operator =

Examples:

diameter = 5.9 ; area = length * width ;

JavaScript Arithmetic Operators

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

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);

10

55

55

55

Comparison Operators

Operator Description Example

== is equal to x==8 is false=== is exactly equal to (value and

type)x===5 is true

x==="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

Example

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

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

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);}

Multiple Selection with if

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

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.") ;}

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}

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

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

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>

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>

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>

Another Example<html>

<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>

Another Example

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>

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>

for...in Statement

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

Syntaxfor (variable in object) { code to be executed }

JavaScript Loops

Looping through the properties of an object:Examplevar person = { fname: "John", lname: "Doe " , age:25 }; 

for (x in person){ document.write(person[x] + " ");}

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

65

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

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

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” ); }}

69

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

SWE444

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.

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

… … … …

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-clickedonMouseDown The user presses the mouse button

onLoad A document or an image is loadedonSubmit A user submits a formonReset The form is reset

onUnLoad The user closes a document or a frameonResize A form is resized by the user

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>

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

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>

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.

<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" ) ; }}

<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<2) {

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

} </script> </head>

<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>

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

<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>

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).

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

actionreaction

Action Event JavaScript DOM Reactionsrc=“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

Object Hierarchy

window

document frame location history

anchor image form link

button checkbox

select

textarea

submit

radio

reset

text

top related