Presentation is loading. Please wait.

Presentation is loading. Please wait.

Client-Side Programming JavaScript Dr. Ahmed Youssef.

Similar presentations


Presentation on theme: "Client-Side Programming JavaScript Dr. Ahmed Youssef."— Presentation transcript:

1 Client-Side Programming JavaScript Dr. Ahmed Youssef

2 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 2 Ahmed Youssef: SWE444: Internet and Web Application Development

3 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 3 Ahmed Youssef: SWE444: Internet and Web Application Development

4 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 4 Ahmed Youssef: SWE444: Internet and Web Application Development

5 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) 5 Ahmed Youssef: SWE444: Internet and Web Application Development

6 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 6 Ahmed Youssef: SWE444: Internet and Web Application Development

7 What can it be used for Text animation graphic animation HTML forms submission client-side forms data validation web site navigation

8 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 8 Ahmed Youssef: SWE444: Internet and Web Application Development

9 Client-Side Programming 9 Ahmed Youssef: SWE444: Internet and Web Application Development

10 Client-side Validating Form information, i.e., making sure all the fields are complete before submitting data back to the server Modifying a web page based on Mouse Events. Can turn a web page into a user interface with interactive buttons and controls 10 Ahmed Youssef: SWE444: Internet and Web Application Development

11 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 11 Ahmed Youssef: SWE444: Internet and Web Application Development

12 Server-Side Programming 12 Ahmed Youssef: SWE444: Internet and Web Application Development

13 Server-side Programming CGI PHP ASP Java Servlet, … Web Client Web Server Internet Client-side Programming XHTML Javascript Dreamweaver Flash XML … Database Server side and Client side Programming 13 Ahmed Youssef: SWE444: Internet and Web Application Development

14 ServerBrowser Request Reply File System Static Web Model 14 Ahmed Youssef: SWE444: Internet and Web Application Development

15 ServerBrowser Request Reply File System Dynamic Web Model Other Programs 15 Ahmed Youssef: SWE444: Internet and Web Application Development

16 Placement of JavaScripts JavaScript can be put in the or in the of an HTML document 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 An external.js file lets you use the same JavaScript on multiple HTML pages 16 Ahmed Youssef: SWE444: Internet and Web Application Development

17 17 The … tag The code for the script is contained in the … tag.

18 Displaying text The document.write() method writes a string of text to the browser document.write(" Hello, world! "); 18 Ahmed Youssef: SWE444: Internet and Web Application Development

19 document.write() document.write(" Hello,world! "); Enclosed in quotes -- denotes a "string" Ends in a semicolon 19 Ahmed Youssef: SWE444: Internet and Web Application Development

20 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: ");

21 Comments in JavaScript Two types of comments Single line Uses two forward slashes (i.e. //) Multiple line Uses /* and */ 21 Ahmed Youssef: SWE444: Internet and Web Application Development

22 Single Line Comment Example // This is my JavaScript comment document.write(" Hello! "); 22 Ahmed Youssef: SWE444: Internet and Web Application Development

23 Multiple Line Comment Example /* 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(" Hello! "); 23 Ahmed Youssef: SWE444: Internet and Web Application Development

24 Find the Bug! /* This is my JavaScript comment * that spans more than 1 line. * document.write(" Hello! "); 24 Ahmed Youssef: SWE444: Internet and Web Application Development

25 JavaScript Statements My Page document.write('This is my first JavaScript Page'); 25 Ahmed Youssef: SWE444: Internet and Web Application Development

26 JavaScript Statements My Page document.write(' This is my first JavaScript Page '); HTML written inside JavaScript 26 Ahmed Youssef: SWE444: Internet and Web Application Development

27 JavaScript Statements My Page <a href="myfile.html" onMouseover="window.alert('Hello');"> My Page JavaScript written inside HTML An Event 27 Ahmed Youssef: SWE444: Internet and Web Application Development

28 Example Statements window.prompt('Enter your name:',''); Note quotes: " and ' 28 Ahmed Youssef: SWE444: Internet and Web Application Development

29 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

30 HTML Forms and JavaScript JavaScript is very good at processing user input in the web browser HTML elements receive input any number of form elements and plain HTML

31 HTML Form Elements This is the initial text spread over two lines First Second

32 Naming Form Elements in HTML Name: Phone: Email: 32 Ahmed Youssef: SWE444: Internet and Web Application Development

33 Forms and JavaScript document.formname.elementname.value document.addressform.yourname.value document.addressform.phone.value document.addressform.email.value 33 Ahmed Youssef: SWE444: Internet and Web Application Development

34 Using Form Data Personalising an alert box Enter your name: 34 Ahmed Youssef: SWE444: Internet and Web Application Development

35 Ahmed Youssef: SWE444: Internet and Web Application Development 35

36 Variables and Arithmetic Operators in JavaScript 36

37 37 Reserved Words (Keywords) in JavaScript abstractdeletefunctionnullthrow booleandogotopackagethrows breakdoubleifprivatetransient byteelseimplementsprotectedtrue caseenumimportpublictry catchexportinreturntypeof charextendsinstanceofshortvar classfalseintstaticvoid constfinalinterfacesupervolatile continuefinallylongswitchwhile debuggerfloatnativesynchronizedwith defaultfornewthis

38 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 39 Which Are Legal Identifiers? AREA 3D lucky***num45 Last-Chance #values x_yt3pi num+%done area_under_the_curve

40 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 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 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 true walletEmpty

43 43 Using Variables: Assignment Uses the assignment operator = Examples: diameter = 5.9 ;area = length * width ;

44 JavaScript Arithmetic Operators Ahmed Youssef: SWE444: Internet and Web Application Development 44 OperatorDescriptionExampleResult +Additionx=y+2x=7y=5 -Subtractionx=y-2x=3y=5 *Multiplicationx=y*2x=10y=5 /Divisionx=y/2x=2.5y=5 %Modulus (division remainder) x=y%2x=1y=5 ++Incrementx=++yx=6y=6 x=y++x=5y=6 --Decrementx=--yx=4y=4 x=y--x=5y=4 Given that y=5, the table below explains the arithmetic operators:

45 JavaScript Assignment Operators Ahmed Youssef: SWE444: Internet and Web Application Development 45 OperatorExampleSame AsResult =x=y x=5 +=x+=yx=x+yx=15 -=x-=yx=x-yx=5 *=x*=yx=x*yx=50 /=x/=yx=x/yx=2 %=x%=yx=x%yx=0 Given that x=10 and y=5, the table below explains the assignment operators:

46 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

47 Comparison Operators Ahmed Youssef: SWE444: Internet and Web Application Development 47 OperatorDescriptionExample ==is equal tox==8 is false ===is exactly equal to (value and type) x===5 is true x==="5" is false !=is not equalx!=8 is true >is greater thanx>8 is false <is less thanx<8 is true >=is greater than or equal tox>=8 is false <=is less than or equal tox<=8 is true

48 Conditional Statements if statement if...else statement if...else if....else statement switch statement Ahmed Youssef: SWE444: Internet and Web Application Development 48

49 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 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 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 52 Multiple Selection with if-else if (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 53 switch Example switch ( 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.") ; }

54 JavaScript Functions How to Define a Function function functionname(var1,var2,...,varX) { some code } Ahmed Youssef: SWE444: Internet and Web Application Development 54

55 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 56 Sample Programmer-Defined Function function PrintMessage() { alert("A message for you:\n\nHave a nice day!"); } PrintMessage(); Function Definition Function Call

57 57 Screenshot of Function Example

58 The return Statement function product(a,b) { return a*b; } document.write(product(4,3)); Ahmed Youssef: SWE444: Internet and Web Application Development 58

59 Example function myFunction() { return ("Hello world!"); } document.write(myFunction()) Ahmed Youssef: SWE444: Internet and Web Application Development 59

60 JavaScript Loops var i=0; for (i=0;i<=5;i++) { document.write("The number is " + i); document.write(" "); } Ahmed Youssef: SWE444: Internet and Web Application Development 60

61 Another Example html> computing factorials Looping example of javascript document.write(" factorial table "); for ( i = 1, fact = 1; i < 10; i++) { fact = fact * I; document.write(i + "! = "+ fact); document.write(" "); } 61

62 Another Example 62

63 JavaScript Loops var i=0; while (i<=5) { document.write("The number is " + i); document.write(" "); i++; } Ahmed Youssef: SWE444: Internet and Web Application Development 63

64 JavaScript Loops var i=0; do { document.write("The number is " + i); document.write(" "); i++; } while (i Ahmed Youssef: SWE444: Internet and Web Application Development 64

65 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

66 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 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 … part

68 68

69 69

70 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 71 onMouseOver=“checkForm( )” JavaScript that goes between the, 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 72

73 73 onClick=“vuWindow()” JavaScript that goes between the, tags: JavaScript included as an attribute of the “New Window” button: function vuWindow() { window.open(“http://www.vu.edu.pk/”) ; }

74 Client-Side Programming JavaScript Dr. Ahmed Youssef

75 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 76 Events defined by JavaScript HTML elements HTML tags JavaScript defined events Description Link<a>clickdblClickmouseDownmouseUpmouseOver Mouse is clicked on a link Mouse is double-clicked on a link Mouse button is pressed Mouse button is released Mouse is moved over a link Image<img>loadaborterror Image is loaded into a browser Image loading is abandoned An error occurs during the image loading Area<area>mouseOvermouseOutdblClick The mouse is moved over an image map area The mouse is moved from image map to outside The mouse is double-clicked on an image map Form<form>submitReset The user submits a form The user refreshes a form …………

77 77 A Few of Event Handlers onClick onDblClick onMouseOver onMouseDown onFocus onBlur onReset onSubmit onLoad onUnload

78 Event 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 79 onLoad event Handler <html><head> onLoad and onUnload Event Handler Example onLoad and onUnload Event Handler Example </head> <body onLoad=”alert(‘Welcome User’)” onUnload=”alert(‘Thanks for visiting the page’)”> Load and UnLoad event test. </body></html>

80 INE2720 – Web Application Software Development All copyright s reserved by C.C. Cheung 2003. 80 User Events, Form Example function dontClick() { alert("I told you not to click!"); } Simple JavaScript Button <input type=“button" value="Don't Click Me" onClick="dontClick()">

81 81 onMouseOver and onMouseOut Event Handlers <a href=“http://www.uoh.edu.sa” onMouseOver = “alert(‘Now mouse is over the link’) “ onMouseOut = “alert (‘Mouse has moved out’)”> A Link Page

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

84 84 <input type="text" name="age" onBlur="checkAge( ) "> JavaScript that goes between the, 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 85 function checkage() { if( document.form1.age.value age phone number

86 Example function valid( ) { var input=document.myform.data.value; if (input<0){ alert("please enter a value that is greater than 0"); } Ahmed Youssef: SWE444: Internet and Web Application Development 86

87 example of onblur event handler: try entering a value less than zero: Ahmed Youssef: SWE444: Internet and Web Application Development 87

88 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

89 North East South West

90 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 91 How the DOM works? <head><script> function toggle() { document.img.button1.src=“button_on.gif”; } </script></head><body> </body> action reaction ActionEventJavaScriptDOMReaction src=“button_off.gif”onmouseovertoggle()document.img.button1Src=“button_on.gif” 1)User moves mouse over object 2)Event senses that something happened to the object 3)JavaScript tells the object what to do (Even handler) 4)Locates object on the web page 5)Object’s image source is changed

92 92 Object Hierarchy window documentframelocationhistory anchorimageformlink buttoncheckbox select textarea submit radio reset text

93 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 94 The “ document ” Object The document object represents a web document or a page in a browser window.

95 95 Properties and methods of the “ document ” Object PropertyDescription bgColorA string value representing the background color of a document alinkColorA string value representing the color for active links locationA string value representing the current URL titleA string value representing the text specified by tag MethodDescription 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 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 97 Properties and methods of the “ history ” Object PropertyDescription lengthAn integer value representing the number of links in the history object currentContains the URL of the current page nextContains the URL of the next entry in the history list previousContains the URL of the previous entry in the history list MethodDescription 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 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 99 Form Validation Script Form Example Form Example function validate() { if (document.form1.yourname.value.length < 1) { if (document.form1.yourname.value.length < 1) { alert("Please enter your full name."); alert("Please enter your full name."); return false; return false; } if (document.form1.address.value.length < 3) { if (document.form1.address.value.length < 3) { alert("Please enter your address."); alert("Please enter your address."); return false; return false; } if (document.form1.phone.value.length < 3) { if (document.form1.phone.value.length < 3) { alert("Please enter your phone number."); alert("Please enter your phone number."); return false; return false; } return true; return true;}</script></head><body> Form Example Form Example Enter the following information. When you press the Display button, the data you entered will be validated, then sent by email. Enter the following information. When you press the Display button, the data you entered will be validated, then sent by email. Name: Name: </p> Address: Address: </p> Phone: Phone: </p> </form></body></html>

100 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


Download ppt "Client-Side Programming JavaScript Dr. Ahmed Youssef."

Similar presentations


Ads by Google