Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 JavaScript. 2 Browser Scripting 3 Client-Server Architecture In a client-server architecture, computation is done either in the client or in the server.

Similar presentations


Presentation on theme: "1 JavaScript. 2 Browser Scripting 3 Client-Server Architecture In a client-server architecture, computation is done either in the client or in the server."— Presentation transcript:

1 1 JavaScript

2 2 Browser Scripting

3 3 Client-Server Architecture In a client-server architecture, computation is done either in the client or in the server There are cases where we can choose whether to perform the computation in the client or in the server -Ex: validating forms There are cases where we cannot choose where to perform the computation -Ex: accessing a database

4 4 Client Side Technologies JavaScript -Developed by Netscape -Supported by all browsers -Most popular scripting language on the web VBScript -Developed by Microsoft -Supported only by Microsoft Internet Explorer -A light version of Microsoft Visual Basic Java Applets -Developed by Sun -A program written in Java that can be included in an HTML page -When you use a Java technology-enabled browser to view a page that contains an applet, the applet's code is transferred to your system and executed by the browser's Java Virtual Machine (JVM).

5 5 Browser Scripting Browser scripts are procedural programs embedded inside HTML script Can read and manipulate HTML elements, CSS properties, and the browser itself

6 6 Why are Scripts Needed? Generating HTML content dynamically Monitoring and responding to user events Validating forms before submission Manipulating HTTP cookies Interaction among the frames and windows of the browser Detecting the visitor's browser

7 7 JavaScript Basics

8 8 JavaScript is NOT Java! JavaScript is not compiled. JavaScript is typically executed by Web browsers and not as stand-alone applications. JavaScript is usually embedded directly into HTML pages. JavaScript and Java have some similarity in syntax, but the choice of the name is mainly for historical reasons.

9 9 script tag The HTML tag is used to insert a JavaScript into an HTML page. Use the type attribute to define the scripting language. document.write(“Hello World!”) standard JavaScript command for writing output to a page

10 10 JavaScript - Example 1: JS Example Before the script document.write(' In the script ') After the script

11 11

12 12 JavaScript - Example 2: JS Example Before the script document.write(new Date().toLocaleString()) After the script

13 13 JavaScript - Example 3: Hello and hours = new Date().getHours(); if (hours < 10) { document.write("good morning") } else {document.write("good day") }.

14 14 Basic Constructs Statement blocks: -Semicolon ( ; ) is optional at end of line var x=5 document.write(x); var x=5, y=7; document.write(x+y); if (condition) {statements if true} else {statements if false} Conditions: if, if-else, ?:, switch x = (y>0)? y:0 Loops: for, while, do-while while (condition) {statements}

15 15 Variables Variables are declared with the var keyword: - var x; var y=5; JavaScript variables do not have a type: - var x = 5; var y = "abcd";... Thus, the value of a variable is characterized by both value and type A variable name consists of letters, digits, and underscores ( _ ), and does not begin with a digit

16 16 Data Types Values have one the following types: -number: 5, 2.3, 0xFF, 6.67e-11 -object: new Date() Arrays: [1,"ab ba",17.234] null -string: "Hello World" -boolean: true, false -undefined: no value assigned... You can use typeof(x) to get the type of x : number, string, object...

17 17 Operators Arithmetic: + ++ - -- * / % Comparison: == != === !== > >= < <= Logical: && || ! Bitwise: & | ^ ~ > String: + Assignments: = += -= *= /=...

18 18 Types of Equality The equals == checks if both operands are equal after performing type conversion The equals === checks if both operands are of the same type and equal Example: -x = 8, y = "8" -x == y returns true -x === y returns false

19 19 An Example for (var counter = 1; counter <= 8; counter ++) { var fontsize = counter + 10; fontsize+="pt"; document.write(" " + "Font size " + fontsize + " "); }

20 20

21 21 Functions

22 22 Functions JavaScript functions are special objects with operator () Syntax: function fname(args...) {statements} Usually, functions are defined at the head of the file Some functions are predefined. Ex: - isNaN(number) - returns false when argument is a number isNaN(2007) - eval(code-string) - gets a string of JavaScript code, evaluates it and executes it eval(“a=3;b=5;document.write(a*b)") Functions can return values

23 23 Function Example function add(x,y) { return x+y; } sum = add(4,5); document.write("4+5="+sum);

24 24 head vs. body Scripts in the head section: -Are executed WHEN CALLED. -When you place a script in the head section, you will ensure that the script is loaded before anyone uses it. -A function contains code that will be executed only by an event or by a call to that function. Functions go in the head section of the document, then we can be sure that the script is loaded before the function is called. Scripts in the body section: -Are executed WHILE THE PAGE LOADS. -When you place a script in the body section it generates the content of the page.

25 25 Function Values Numbers and Booleans are passed to functions by value Objects and strings are passed to functions by reference Numbers and Boolean values are always returned by value Objects and strings are returned by reference

26 26 Undeclared Arguments Function may receive arguments without declaring them Within a function, its arguments are held in the arguments array -can be accessed with arguments[i] -The number of arguments is arguments.length Hence, it is possible to define functions that take any number of arguments

27 27 An Example What is the result of the following code? function myConcat(separator) { var result=""; // iterate through arguments for (var i=1; i<arguments.length; i++) { result += arguments[i] + separator; } return result; } con = myConcat(",", "red", "orange", "blue"); red, orange, blue,

28 28 Variable Scopes JavaScript variables are recognized inside their declaration scope. A variable declared within a function can only be accessed within that function. When you exit the function, the variable is destroyed. Hence, global variables should be declared outside the functions. The lifetime of global variables starts when they are declared, and ends when the page is closed. A variable declared in a function can also be global, if var is omitted.

29 29 Example: Variables var b = 10; disp_a(); function disp_a() { a = 20; alert("Value of 'a' inside the function " + a); } alert("Value of 'b' outside the function " + b); alert("Value of 'a' outside the function " + a);

30 30 Objects and Arrays

31 31 Object Model JavaScript objects are similar to associative arrays That is, an object associates identifiers (e.g., firstName ) 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 object.func() is invoked, object can be referred to as this

32 32 Creating Objects Objects can be created in several ways: I.Object Initializers II.Object Assignments var theNissan = {make:"Nissan", year:2003, color:"blue"} theMazda = { make:"Nissan" } theMazda.year = 2002; theMazda.color="black";

33 33 Creating Objects (cont) III.Object Constructors define a constructor function create the new object using new function car(make,year,color) { this.make = make this.year = year this.color = color } theHonda = new car("Honda", 2001, "green")

34 34 Defining Methods Methods are associated with objects just like attributes function niceString() { return " " + this.make + " "+ this.year + " " } theNissan = {make:"Nissan",year:2003,color:"blue",str:niceString} Can use “this” here because it will run in the scope of the object

35 35 Defining Methods (cont) function car(make,year,color) { this.make = make this.year = year this.color = color this.str = niceString } theHonda = new car("Honda", 2001, "green") theNissan = {make:"Nissan", year:2003, color:"blue"} theNissan.str = niceString;

36 36 Accessing Object Properties Object attributes can be accessed in several ways: - object.attName - object["attName"] Thus, object methods are invoked in Java/C++ style: - object.method(arguments) Alternatively: - object["method"](arguments)

37 37 The Complete Example function niceString() { return " " + this.make + " "+ this.year + " " } function car(make,year,color) { this.make = make; this.year = year; this.color = color; this.str = niceString } var theHonda = new car("Honda", 2001, "green"); document.write(theHonda.str()); constructor

38 38 Array Objects Arrays are supported as objects Attribute length Methods include: concat, join, pop, push, reverse, sort, shift,... Arrays can be passed to functions as arguments The array is passed by-reference

39 39 Creating Arrays var a = new Array("red", "blue", "green") -Allocates an array of 3 cells and initializes the values var b = new Array(5) -Allocates an array of 5 cells without initializing values var c = new Array() -Creates a new empty array

40 40 Array Elements Array elements need not have the same type - arr1 = ["hello", 1, true] Java-like access: arr[i] 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]]

41 41 for…in var x var myfavoritecolors = new Array() myfavoritecolors[0] = "blue" myfavoritecolors[1] = "red" myfavoritecolors[2] = "purple" for (x in myfavoritecolors) { document.write(myfavoritecolors[x] + " ") }

42 42 Miscellaneous

43 43 Import JavaScript You might want to run the same JavaScript on several pages, without having to write the same script on every page. Write a JavaScript in an external file. Save the external JavaScript file with a.js file extension. Import the JavaScript code:

44 44 try…catch The try...catch statement allows you to test a block of code for errors. The try block contains the code to be run The catch block contains the code to be executed if an error occurs.

45 45 try…catch example: try { aalert("Welcome guest!") } catch(err) { var txt="There was an error on this page.\n\n" ; txt+="Error description: " + err.description + "\n\n" ; txt+="Click OK to continue.\n\n“; alert(txt); }

46 46 The String Object JavaScript has a built-in String object -not the primitive string ! Create a String object from a string primitive: - myString = new String("This is a string object") Extract the primitive string from a String object: - str = myString.valueOf()

47 47 String Common Methods charAt (index) charCodeAt(index) concat(string) toLowerCase() toUpperCase() valueOf() split(seperator) substr(startIndex, length) substring(startIndex, endIndex) indexOf(substring, fromIndex) slice(startIndex, endIndex) match(searchValue)

48 48 An Example - Format Verification What does the following function do? function getString() { var result = null; while(result==null) { var answer = prompt("Your first name:") if(answer!=null) { result = new String(answer); result = result.toLowerCase().match("^[a-z]+$"); } if(result==null) { alert("Don't mess with me!") } } return answer }

49 49 The Math Object The object Math is used for mathematical operations -E.g., Math.pow(x,2) Other useful functions: abs(x) round(x) floor(x) random() cos(x) sin(x) tan(x) exp(x) pow(x, y) sqrt(x) log(x) max(x, y) Math also includes constants such as: Math.E, Math.PI

50 50 The with Statement Establishes the default object for a set of statements Within the set of statements, any property references that do not specify an object are assumed to be of the default object var a, x, y var r=10 with (Math) { a = PI * r * r; x = r * cos(PI); y = r * sin(PI/2) }

51 51 The Date Object Create the current date: new Date() Create an arbitrary date: new Date( date-string ) Common methods of Date : getDate() getFullYear() getMonth() getDay getTime() getHours() getMinutes() getSeconds() getMilliseconds() toLocaleString()

52 52 An Example - Clock function startTime() { var today = new Date() var h = today.getHours() var m = today.getMinutes() var s = today.getSeconds() // add a zero in front of numbers<10 m = checkTime(m) s = checkTime(s) document.getElementById('txt').innerHTML = h+":"+m+":"+s t=setTimeout('startTime()',500) } function checkTime(i) { if (i<10) {i="0" + i} return i }

53 53 The End! These slides are based on those developed for the course: http://www.cs.huji.ac.il/~dbi http://www.cs.huji.ac.il/~dbi More information about JavaScript can be found at: http://www.w3schools.com/js/default.asp http://www.pageresource.com/jscript/ http://www.htmlgoodies.com/primers/jsp/


Download ppt "1 JavaScript. 2 Browser Scripting 3 Client-Server Architecture In a client-server architecture, computation is done either in the client or in the server."

Similar presentations


Ads by Google