530 likes | 650 Views
JavaScript. Browser Scripting. 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
E N D
Client-Server Architecture • In aclient-server architecture, computation is done either in the clientor in theserver • 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
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).
Browser Scripting • Browser scripts are procedural programs embedded inside HTML <script type="text/javascript">script</script> <script type="text/vbscript">script</script> • Can read and manipulate HTML elements, CSS properties, and the browser itself
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
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.
script tag • The HTML <script> tag is used to insert a JavaScript into an HTML page. Use the type attribute to define the scripting language. <script type="text/javascript"> document.write(“Hello World!”) </script> standard JavaScript command for writing output to a page
JavaScript - 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>
JavaScript - Example 2: <html> <head><title>JS Example</title></head><body> <h2>Before the script</h2> <h1><script type="text/javascript"> document.write(new Date().toLocaleString()) </script></h1> <h2>After the script</h2> </body></html>
JavaScript - Example 3: <h2>Hello and <i><script type="text/javascript"> hours =new Date().getHours(); if(hours <10){ document.write("good morning")} else{document.write("good day")} </script></i>. </h2>
Basic Constructs • Statement blocks: • Semicolon (;) is optional at end of line var x=5, y=7; document.write(x+y); var x=5 document.write(x); • Conditions: if, if-else, ?:, switch if (condition) {statements if true} else {statements if false} x = (y>0)? y:0 • Loops: for, while, do-while • while (condition) {statements}
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
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 ofx: number, string, object...
Operators • Arithmetic: + ++ - -- * / % • Comparison: == != === !== > >= < <= • Logical: && || ! • Bitwise: & | ^ ~ << >> • String: + • Assignments: = += -= *= /= ...
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
An Example <script type="text/javascript"> for(varcounter =1; counter <=8; counter ++){ var fontsize= counter +10; fontsize+="pt"; document.write("<p style=font-size: "+fontsize+">" +"Font size "+fontsize+"</p>"); } </script>
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
Function Example <html> <head> <script type="text/javascript"> functionadd(x,y){ return x+y; } </script> </head> <body> <h1> <script type="text/javascript"> sum =add(4,5); document.write("4+5="+sum); </script> </h1></body> </html>
head vs. body • Scripts in the head section: • Are executed WHENCALLED. • 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 WHILETHE PAGE LOADS. • When you place a script in the body section it generates the content of the page.
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
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
An Example What is the result of the following code? functionmyConcat(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,
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.
Example: Variables <body><script type="text/javascript"> 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); </script></body>
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
Creating Objects • Objects can be created in several ways: • Object Initializers • Object Assignments var theNissan ={make:"Nissan", year:2003, color:"blue"} theMazda ={ make:"Nissan"} theMazda.year =2002; theMazda.color="black";
Creating Objects (cont) • ObjectConstructors • define a constructor function • create the new object using new functioncar(make,year,color) { this.make = make this.year = year this.color = color } theHonda =newcar("Honda",2001,"green")
Defining Methods • Methods are associated with objects just like attributes function niceString() { return"<span style='color:"+this.color +"'>"+ this.make +" "+this.year +"<\/span>" } theNissan = {make:"Nissan",year:2003,color:"blue",str:niceString} Can use “this” here because it will run in the scope of the object
Defining Methods (cont) theNissan={make:"Nissan", year:2003, color:"blue"} theNissan.str = niceString; functioncar(make,year,color) { this.make = make this.year = year this.color = color this.str = niceString } theHonda =newcar("Honda",2001,"green")
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)
The Complete Example function niceString() { return"<span style='color:"+this.color +"'>"+ this.make +" "+this.year +"<\/span>" } functioncar(make,year,color) { this.make = make; this.year = year; this.color = color; this.str = niceString } var theHonda =newcar("Honda",2001,"green"); document.write(theHonda.str()); constructor
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
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
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]]
for…in <script type="text/javascript"> var x var myfavoritecolors = new Array() myfavoritecolors[0] = "blue" myfavoritecolors[1] = "red" myfavoritecolors[2] = "purple" for (x inmyfavoritecolors) { document.write(myfavoritecolors[x] + "<br />")} </script>
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: <script type="..." src="jsfile.js"/>
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.
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); }
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()
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) String Common Methods
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 }
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
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) }