Java Script Language Fundamentals 26 Jan22 About Java

Java. Script Language Fundamentals 26 -Jan-22

About Java. Script • Java. Script is not Java, or even related to Java – The original name for Java. Script was “Live. Script” – The name was changed when Java became popular – Now that Microsoft no longer likes Java, its name for their Java. Script dialect is “Active Script” • Statements in Java. Script resemble statements in Java, because both languages borrowed heavily from the C language – Java. Script should be fairly easy for Java programmers to learn – However, Java. Script is a complete, full-featured, complex language • Java. Script is seldom used to write complete “programs” – Instead, small bits of Java. Script are used to add functionality to HTML pages – Java. Script is often used in conjunction with HTML “forms” • Java. Script is reasonably platform-independent 2

Using Java. Script in a browser • Java. Script code is included within <script> tags: – <script type="text/javascript"> document. write("<h 1>Hello World!</h 1>") ; </script> • Notes: – The type attribute is to allow you to use other scripting languages (but Java. Script is the default) – This simple code does the same thing as just putting <h 1>Hello World!</h 1> in the same place in the HTML document – The semicolon at the end of the Java. Script 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 3

Where to put Java. Script • Java. Script can be put in the <head> or in the <body> of an HTML document – Java. Script functions should be defined in the <head> • This ensures that the function is loaded before it is needed – Java. Script in the <body> will be executed as the page loads • Java. Script can be put in a separate. js file – <script src="my. Java. Script. File. js"></script> – Put this HTML wherever you would put the actual Java. Script code – An external. js file lets you use the same Java. Script on multiple HTML pages – The external. js file cannot itself contain a <script> tag • Java. Script can be put in an HTML form object, such as a button – This Java. Script will be executed when the form object is used 4

Primitive data types • Java. Script has three “primitive” types: number, string, and boolean – Everything else is an object • Numbers are always stored as floating-point values • Strings may be enclosed in single quotes or double quotes – Strings can contains n (newline), " (double quote), etc. • Booleans are either true or false – 0, "0", empty strings, undefined, null, and Na. N are false , other values are true 5

Variables • Variables are declared with a var statement: – – – var pi = 3. 1416, x, y, name = "Dr. Dave" ; 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) • Variables declared within a function are local to that function (accessible only within that function) • Variables declared outside a function are global (accessible from anywhere on the page) 6

Operators, I • Because most Java. Script syntax is borrowed from C (and is therefore just like Java), we won’t spend much time on it • Arithmetic operators (all numbers are floating-point): + * / % ++ - • Comparison operators: < <= == != >= > • Logical operators: && || ! (&& and || are short-circuit operators) • Bitwise operators: & | ^ ~ << >> >>> • Assignment operators: += -= *= /= %= <<= >>>= &= ^= |= 7

Operators, II • String operator: + • The conditional operator: condition ? value_if_true : value_if_false • Special equality tests: – == and != try to convert their operands to the same type before performing the test • Additional operators (to be discussed): new typeof void delete 8

Comments • Comments are as in C or Java: – Between // and the end of the line – Between /* and */ 9

Statements, I • Most Java. Script statements are also borrowed from C – Assignment: greeting = "Hello, " + name; – Compound statement: { statement; . . . ; statement } – If statements: if (condition) statement; else statement; – Familiar loop statements: while (condition) statement; do statement while (condition); for (initialization; condition; increment) statement; 10

Statements, II • The switch statement: switch (expression) { case label : statement; break; . . . default : statement; } • Other familiar statements: – break; – continue; – The empty statement, as in ; ; or { } 11

Java. Script is not Java • By now you should have realized that you already know a great deal of Java. Script – So far we have talked about things that are the same as in Java • Java. Script has some features that resemble features in Java: – Java. Script has Objects and primitive data types – Java. Script has qualified names; for example, document. write("Hello World"); – Java. Script has Events and event handlers – Exception handling in Java. Script is almost the same as in Java • Java. Script 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 – Java. Script has with statements and a new kind of for statement 12

Exception handling, I • Exception handling in Java. Script is almost the same as in Java • throw expression creates and throws an exception – The expression is the value of the exception, and can be of any type (often, it's a literal String) • try { statements to try } catch (e) { // Notice: no type declaration for e exception handling statements } finally { // optional, as usual code that is always executed } – With this form, there is only one catch clause 13

Exception handling, II • try { statements to try } catch (e if test 1) { exception handling for the case that test 1 is true } catch (e if test 2) { exception handling for when test 1 is false and test 2 is true } catch (e) { exception handling for when both test 1 and test 2 are false } finally { // optional, as usual code that is always executed } • Typically, the test would be something like e == "Invalid. Name. Exception" 14

Objects • Is a collection of related properties and methods. • Properties represent features and Methods represent action that can be performed on that objects. • Objects of same class may have different set of properties and methods. 15

Object literals • Java. Script has object literals. • An object literal is a comma-separated list of name-value pairs written within a pair of curly braces written with this syntax: object. Name={ Propertyname 1 : value 1 , . . . , Propertyname. N : value. N } • Example: – P= {x: 2, y: 3} ; // It creates object P having two properties x and y and have values 2 and 3. 16

Cont… – Properties of an object is accessed by the dot(. ) operator as: P. x and P. y – Properties may also be added later, as: P. color=“red” 17

Three ways to create an object • You can use an object literal: – var course = { number: "CIT 597", teacher: "Dr. Dave" } • You can use new to create a “blank” object, and add fields to it later: – var course = new Object(); course. number = "CIT 597"; course. teacher = "Dr. Dave"; • You can write and use a constructor. A class in Java. Script is defined by a function which act as the constructor for the class. Objects are created with the help of this constructor function and the new operator, as : – function Course(n, t) { // best placed in <head> this. number = n; // keyword "this" is required, not optional this. teacher = t; } – var course = new Course("CIT 597", "Dr. Dave"); – this: The constructor has a reference this that refers to the newly created object for which the constructor was invoked. – The this reference may be used to access the object’s properties and methods. 18

Cont. . • Example function draw(x, y) { this. x=x; this. y=y; } p=new draw(3, 4); So, this refers to object p and this. x and this. y refer to p. x and p. y repectively. 19

The for…in statement • You can loop through all the properties of an object with for (variable in object) statement; – Example: for (var prop in course) { document. write(prop + ": " + course[prop]); } – Possible output: teacher: Dr. Dave number: CIT 597 – The properties are accessed in an undefined order – Arrays are objects; applied to an array, for…in will visit the “properties” 0, 1, 2, … – Notice that course["teacher"] is equivalent to course. teacher • You must use brackets if the property name is in a variable 20

Array literals • Java. Script has array literals, written with brackets and commas – Example: color = ["red", "yellow", "green", "blue"]; – Arrays are zero-based: color[0] is "red" • If you put two commas in a row, the array has an “empty” element in that location – Example: color = ["red", , , "green", "blue"]; • color has 5 elements – However, a single comma at the end is ignored • Example: color = ["red", , , "green", "blue”, ]; still has 5 elements 21

Four ways to create an array • You can use an array literal: var colors = ["red", "green", "blue"]; • You can use new Array() to create an empty array: – var colors = new Array(); – You can add elements to the array later: colors[0] = "red"; colors[2] = "blue"; colors[1]="green"; • You can use new Array(n) with a single numeric argument to create an array of that size – var colors = new Array(3); • You can use new Array(…) with two or more arguments to create an array containing those values: – var colors = new Array("red", "green", "blue"); 22

The length of an array • If my. Array is an array, its length is given by my. Array. length • Array length can be changed by assignment beyond the current length – Example: var my. Array = new Array(5); my. Array[10] = 3; • Arrays are sparse, that is, space is only allocated for elements that have been assigned a value – Example: my. Array[50000] = 3; is perfectly OK – But indices must be between 0 and 232 -1 • You can have an array of arrays: my. Array[5][3] 23

Arrays and objects • Arrays are objects • car = { my. Car: "Saturn", 7: "Mazda" } – car[7] is the same as car. 7 – car. my. Car is the same as car["my. Car"] • If you know the name of a property, you can use dot notation: car. my. Car 24

Array functions If my. Array is an array, – my. Array. sort() sorts the array alphabetically – my. Array. reverse() reverses the array elements – my. Array. push(…) adds any number of new elements to the end of the array, and increases the array’s length – my. Array. pop() removes and returns the last element of the array, and decrements the array’s length – my. Array. unshift() adds one or more elements to the beginning of an array and returns the new length of the array. – my. Array. shift() Removes the first element from an array and decrements the array’s length. – my. Array. join()joins all elements of an array into a string. 25

Date Object • Date()Returns today's date and time • get. Date()Returns the day of the month(1 -31) for the specified date. • get. Day()Returns the day of the week(0 -6) for the specified date. • get. Full. Year()Returns the 4 -digit year component of the specified date. • get. Hours()Returns the hour (0 -23)in the specified date. • get. Milliseconds()Returns the milliseconds(0 -999) in the specified date. 26

Cont. . • get. Minutes()Returns the minutes (0 -59)in the specified date. • get. Month()Returns the month(0 -11) in the specified date. • get. Seconds()Returns the seconds in the specified date according to local time. • set. Full. Year() Sets the year component of the date using 4 -digit number. • Set. Month() , Set. Date() • Set. Hours() , Set. Minutes(), Set. Seconds() , Set. Milliseconds() 27

Reg. Exp class • A regular expression is an object that describes a pattern of characters. • The Java. Script Reg. Exp class represents regular expressions, and both String and Reg. Exp define methods that use regular expressions to perform powerful pattern-matching and search-and-replace functions on text. 28

Cont… Syntax: • A regular expression could be defined with the Reg. Exp( ) constructor like this: • var pattern = new Reg. Exp(pattern, attributes); or simply var pattern = /pattern/attributes; Here is the description of the parameters: • pattern: A string that specifies the pattern of the regular expression. • attributes: An optional string containing any of the "g", "i", and "m" attributes that specify global, caseinsensitive, and multiline matches, respectively. 29
![Cont… • [. . . ]Any one character between the brackets. • [^. . Cont… • [. . . ]Any one character between the brackets. • [^. .](http://slidetodoc.com/presentation_image_h2/94bd22a9d2743a05fadc60b338155b74/image-30.jpg)
Cont… • [. . . ]Any one character between the brackets. • [^. . . ]Any one character not between the brackets. • [0 -9]It matches any decimal digit from 0 through 9. • [a-z]It matches any character from lowercase a through lowercase z. • [A-Z]It matches any character from uppercase A through uppercase Z. • [a-Z]It matches any character from lowercase a through uppercase Z. 30

Regular expressions • A regular expression can be written in either of two ways: – Within slashes, such as re = /ab+c/ – With a constructor, such as re = new Reg. Exp("ab+c") • string. match(regexp) searches string for an occurrence of regexp – It returns null if nothing is found – If regexp has the g (global search) flag set, match returns an array of matched substrings – If g is not set, match returns an array whose 0 th element is the matched text, extra elements are the parenthesized subexpressions, and the index property is the start position of the matched substring 31

The with statement • with (object) statement ; uses the object as the default prefix for variables in the statement • For example, the following are equivalent: – with (document. my. Form) { result. value = compute(my. Input. value) ; } – document. my. Form. result. value = compute(document. my. Form. my. Input. valu e); 32

Functions • Functions should be defined in the <head> of an HTML page, to ensure that they are loaded first • The syntax for defining a function is: function name(arg 1, …, arg. N) { statements } – The function may contain return value; statements – Any variables declared within the function are local to it • The syntax for calling a function is just name(arg 1, …, arg. N) • Simple parameters are passed by value, objects are passed by reference 33

Warnings • Java. Script is a big, complex language – Write and test your programs a little bit at a time • Java. Script is not totally platform independent – Expect different browsers to behave differently – Write and test your programs a little bit at a time • Browsers aren’t designed to report errors – Don’t expect to get any helpful error messages 34

Evaluation (i. e. , Dave’s opinion) • Java. Script, like Java, is in the C family of languages • Java. Script has lots of convenience features – Global variables – Not having to declare variables at all – Untyped variables – Easy modification of objects • Java. Script is designed for programming in the small, not for large programs – Many features, such as global variables, are bad news for large programs 35

Browser support • Java. Script works on almost all browsers • Internet Explorer uses JScript (referred to in menus as “Active Scripting”), which is Microsoft’s dialect of Java. Script • Older browsers don’t support some of the newer features of Java. Script – We will assume modern browser support 36

Strings and characters • In Java. Script, string is a primitive type • Strings are surrounded by either single quotes or double quotes • There is no “character” type • Special characters are: b f n r t NUL backspace form feed newline carriage return horizontal tab v ' " \ vertical tab single quote double quote backslash 37

Some string methods • char. At(n) – Returns the nth character of a string • concat(string 1, . . . , string. N) – Concatenates the string arguments to the recipient string • index. Of(substring) – Returns the position of the first character of substring in the recipient string, or -1 if not found • index. Of(substring, start) – Returns the position of the first character of substring in the given string that begins at or after position start, or -1 if not found • last. Index. Of(substring), last. Index. Of(substring, start) – Like index. Of, but searching starts from the end of the recipient string 38

More string methods • match(regexp) – Returns an array containing the results, or null if no match is found – On a successful match: • If g (global) is set, the array contains the matched substrings • If g is not set: – Array location 0 contains the matched text – Locations 1. . . contain text matched by parenthesized groups – The array index property gives the first matched position • replace(regexp, replacement) – Returns a new string that has the matched substring replaced with the replacement • search(regexp) – Returns the position of the first matched substring in the given string, or -1 if not found. 39

boolean • The boolean values are true and false • When converted to a boolean, the following values are also false: – 0 – "0" and '0' – The empty string, '' or "" – undefined – null – Na. N 40

undefined and null • There are special values undefined and null • undefined is the only value of its “type” – This is the value of a variable that has been declared but not defined, or an object property that does not exist – void is an operator that, applied to any value, returns the value undefined • null is an “object” with no properties 41

Arrays • As in C and Java, there are no “true” multidimensional arrays – However, an array can contain arrays – The syntax for array reference is as in C and Java • Example: var a = [ ["red", 255], ["green", 128] ]; var b = a[1][0]; // b is now "green" var c = a[1]; // c is now ["green", 128] 42

Determining types • The unary operator typeof returns one of the following strings: "number", "string", "boolean", "object", "undefined", and "function“ – typeof null is "object" – If my. Array is an array, typeof my. Array is "object“ 43

Wrappers and conversions • Java. Script has “wrapper” objects for when a primitive value must be treated as an object – – var s = new String("Hello"); // s is now a String var n = new Number(5); // n is now a Number var b = new Boolean(true); // b is now a Boolean Because Java. Script does automatic conversions as needed, wrapper objects are hardly ever needed • Java. Script has no “casts, ” but conversions can be forced – – var s = x + ""; // s is now a string var n = x + 0; // n is now a number var b = !!x; // b is now a boolean Because Java. Script does automatic conversions as needed, explicit conversions are hardly ever needed 44

Variables • Every variable is a property of an object • When Java. Script starts, it creates a global object • In client-side Java. Script, the window is the global object – It can be referred to as window or as this – The “built-in” variables and methods are defined here • There can be more than one “global” object – For example, one frame can refer to another frame with code such as parent. frames[1] • Local variables in a function are properties of a special call object 45

Functions • In Java. Script, a function is an object • Functions can be recursive: – function factorial(n) { if (n <= 1) return 1; else return n * factorial(n - 1); } • Functions can be nested: – function hypotenuse(a, b) { function square(x) { return x * x; } return Math. sqrt(square(a) + square(b)); } 46

The Function() constructor • Since functions are objects, they have a constructor: – Function(arg 1, arg 2, . . . , arg. N, body) – All the arguments to the constructor are strings – Example: var f = new Function("x", "y", "return x * y; "); • Notice that the function has no name – But you can assign it to a variable and use that name – The name can be used to call the function as usual • You can construct functions dynamically in Java. Script (they are automatically compiled) – However, compilation is computationally expensive • Functions defined in this way are always global 47

Function literals • As we just saw, a function can be defined by means of a constructor: – var f = new Function("x", "y", "return x * y; "); • A function can be written literally, as in the following example: – var f = function(x, y) { return x * y; } – This function is not necessarily global 48

Function names • The “name” of a function is just the variable that holds the function – var square = function(x) { return x * x; }; – var a = square(4); // a now holds 16 – var b = square; // b now holds square – var c = b(5); // c now holds 25 49

The call object • When a function is called, a new call object is created – The properties of the call object include: • The function parameters • Local variables declared with the var statement • The arguments object 50
![arguments • The arguments object is like an array – arguments[n] is a synonym arguments • The arguments object is like an array – arguments[n] is a synonym](http://slidetodoc.com/presentation_image_h2/94bd22a9d2743a05fadc60b338155b74/image-51.jpg)
arguments • The arguments object is like an array – arguments[n] is a synonym for the nth argument – arguments. length is the number of arguments that the function was called with • function. length is the number of arguments it was defined with • arguments. length, unlike function. length, is available only within the function – arguments. callee is the function itself 51

Methods • When a function is a property of an object, we call it a “method” – A method can be invoked by either of call(object, arg 1, . . . , arg. N) or apply(object, [arg 1, . . . , arg. N]) – call and apply are defined for all functions • call takes any number of arguments • apply takes an array of arguments – Both allow you to invoke a function as if it were a method of some other object, object – Inside the function, the keyword this refers to the object 52

Functions Overloading • Javascript functions are not polymorphic. • It does not distinguish functions with respect to number of parameters declared within them. • The total number of arguments may be obtained using the length property of arguments array. 53

Example • public string Cat. Strings(string p 1) {return p 1; } • public string Cat. Strings(string p 1, int p 2) {return p 1+p 2. To. String(); } • public string Cat. Strings(string p 1, int p 2, bool p 3) {return p 1+p 2. To. String()+p 3. To. String(); } Cat. Strings("one"); // result = one Cat. Strings("one", 2); // result = one 2 Cat. Strings("one", 2, true); // result = one 2 true 54

Cont… Java. Script Equivalent: • function Cat. Strings(p 1, p 2, p 3) { var s = p 1; if(typeof p 2 !== "undefined") {s += p 2; } if(typeof p 3 !== "undefined") {s += p 3; } return s; }; Cat. Strings("one"); // result = one Cat. Strings("one", 2); // result = one 2 Cat. Strings("one", 2, true); // result = one 2 true Program 55

The End 56

Java. Script and HTML Simple Event Handling 26 -Jan-22

Java. Script and DOM • Every web page resides inside a browser window which can be considered as an object. • A Document object represents the HTML document that is displayed in that window. The Document object has various properties that refer to other objects which allow access to and modification of document content. • The way that document content is accessed and modified is called the Document Object Model, or DOM. The Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a Web document. 58

HTML names in Java. Script • In HTML the window is the global object – It is assumed that all variables are properties of this object, or of some object descended from this object – The most important window property is document • HTML form elements can be referred to by document. forms[form. Number]. elements[element. Number] • Every HTML form element has a name attribute – The name can be used in place of the array reference – Hence, if • <form name="my. Form"> <input type="button" name="my. Button". . . > • Then instead of document. forms[0]. elements[0] • you can say document. my. Form. my. Button 59

Cont. . • Window object: Top of the hierarchy. It is the outmost element of the object hierarchy. • Document object: Each HTML document that gets loaded into a window becomes a document object. The document contains the content of the page. • Form object: Everything enclosed in the <form>. . . </form> tags sets the form object. • Form control elements: The form object contains all the elements defined for that object such as text fields, buttons, radio buttons, and checkboxes. 60

Here is a simple hierarchy of few important objects: 61

The Document Object • When an HTML document is loaded into a web browser, it becomes a document object(DO). • DO is the root node of the HTML document and is the “container” of all other nodes, like element nodes, text nodes, attribute nodes, and comment nodes. • DO provides properties and methods to access all node objects, from within Java. Script. • The document is a part of the window object and can be accessed as window. document. 62

Finding HTML Elements Method • document. get. Element. By. Id(): Finding an element by element id • document. get. Elements. By. Tag. Name(): Finding elements by tag name • document. get. Elements. By. Class. Name(): Finding elements by class name • document. forms[] : Finding elements by HTML element objects 63

Adding and Deleting Elements Method • document. create. Element(): Create an HTML element • document. remove. Child(): Remove an HTML element. • document. append. Child() : Add an HTML element. • document. replace. Child() : replace an HTML element Adding Events Handlers • document. get. Element. By. Id(id). onclick=function(){cod e}: Adding event handler code to an onclick event 64

Adding and Removing Nodes (HTML Elements) • • • • <html> <body> <div id="div 1"> <p id="p 1">This is a paragraph. </p> <p id="p 2">This is another paragraph. </p> </div> <script> var para=document. create. Element("p"); var node=document. create. Text. Node("This is new. "); para. append. Child(node); var element=document. get. Element. By. Id("div 1"); element. append. Child(para); </script> </body> </html> 65

Creating new HTML Elements - insert. Before() • The append. Child() method appends the new element as the last child of the parent. To use the insert. Before() method: Example • <div id="div 1"> <p id="p 1">This is a paragraph. </p> <p id="p 2">This is another paragraph. </p> </div> <script> var para=document. create. Element("p"); var node=document. create. Text. Node("This is new. "); para. append. Child(node); var element=document. get. Element. By. Id("div 1"); var child=document. get. Element. By. Id("p 1"); element. insert. Before(para, child); </script> 66

Removing Existing HTML Elements • To remove an HTML element, you must know the parent of the element: Example • <div id="div 1"> <p id="p 1">This is a paragraph. </p> <p id="p 2">This is another paragraph. </p> </div> <script> var parent=document. get. Element. By. Id("div 1"); var child=document. get. Element. By. Id("p 1"); parent. remove. Child(child); </script> 67

Window Object Properties • closed. Returns a Boolean value indicating whether a window has been closed or not • default. Status. Sets or returns the default text in the statusbar of a window • document. Returns the Document object for the window frames. Returns an array of all the frames (including iframes) in the current window • history. Returns the History object for the window • length. Returns the number of frames (including iframes) in a window • location. Returns the Location object for the window Sets 68 or returns the name of a window

Cont. . • navigator. Returns the Navigator object for the window • parent. Returns the parent window of the current window • screen. Top. Returns the y coordinate of the window relative to the screen • screen. XReturns the x coordinate of the window relative to the screen • screen. YReturns the y coordinate of the window relative to the screen • self. Returns the current window • status. Sets or returns the text in the statusbar of a window • top. Returns the topmost browser window 69

Window Object Methods • alert()Displays an alert box with a message and an OK button • blur()Removes focus from the current window • close()Closes the current window • confirm()Displays a dialog box with a message and an OK and a Cancel button • create. Popup()Creates a pop-up window • focus()Sets focus to the current window • move. By()Moves a window relative to its current position 70

Cont. . • move. To()Moves a window to the specified position • open()Opens a new browser window • print()Prints the content of the current window • prompt()Displays a dialog box that prompts the visitor for input • resize. By()Resizes the window by the specified pixels • stop()Stops the window from loading 71

Location Object • The location object is part of the window object and is accessed through the window. location property. • The location object contains information about the current URL. Properties • host. Sets or returns the hostname and port number of a URL • hostname. Sets or returns the hostname of a URL 72

Cont… • href Sets or returns the entire URL • pathname. Sets or returns the path name of a URL • port. Sets or returns the port number of a URL • protocol. Sets or returns the protocol of a URL • search. Sets or returns the query portion of a URL Method • reload() Reloads the current document • replace()Replaces the current document with a new one 73

History Object • The history object is part of the window object and is accessed through the window. history property. • The history object contains the URLs visited by the user (within a browser window). Properties • length Returns the number of URLs in the history list • next Returns next URL in the history object. • previous Returns previous URL in the history object. • current Returns current URL 74

Cont… Method back() Loads previous URL in the history list forward() Loads next URL in the history list go() Loads a specific URL in the history list 75

Window History Back The history. back() method loads the previous URL in the history list. Example: Create a back button on a page: • <html> <head> <script> function go. Back() { window. history. back() } </script> </head> <body> <input type="button" value="Back" onclick="go. Back()"> </body> </html> 76

Navigator Object • The navigator object contains information about the client’s browser such as its name and version. Properties app. Code. Name: Returns the code name of the browser app. Name. Returns the name of the browser app. Version. Returns the version information of the browser cookie. Enabled. Determines whether cookies are enabled in the browser language. Returns the language of the browser on. Line. Determines whether the browser is online platform. Returns for which platform the browser is compiled 77

Cont… • • • • • <!DOCTYPE html> <body> <div id="example"></div> <script> txt = "<p>Browser Code. Name: " + navigator. app. Code. Name + "</p>"; txt+= "<p>Browser Name: " + navigator. app. Name + "</p>"; txt+= "<p>Browser Version: " + navigator. app. Version + "</p>"; txt+= "<p>Cookies Enabled: " + navigator. cookie. Enabled + "</p>"; txt+= "<p>Browser Language: " + navigator. language + "</p>"; txt+= "<p>Browser Online: " + navigator. on. Line + "</p>"; txt+= "<p>Platform: " + navigator. platform + "</p>"; txt+= "<p>User-agent header: " + navigator. user. Agent + "</p>"; txt+= "<p>User-agent language: " + navigator. system. Language + "</p>"; document. get. Element. By. Id("example"). inner. HTML=txt; </script> </body> </html> 78

the inner. HTML • Example • The following code gets the content (the inner. HTML) of the <p> element with id="intro": • Example • <html> <body> <p id="intro">Hello World!</p> <script> var txt=document. get. Element. By. Id("intro"). inner. HTML; document. write(txt); </script> </body> </html> 79

Cont… • In the example above, get. Element. By. Id is a method, while inner. HTML is a property. • The get. Element. By. Id Method • The most common way to access an HTML element is to use the id of the element. • In the example above the get. Element. By. Id method used id="intro" to find the element. • The inner. HTML Property • The easiest way to get the content of an element is by using the inner. HTML property. • The inner. HTML property is useful for getting or replacing the content of HTML elements. 80

Events • Some (but not all) elements on the web page respond to user interactivity (keystrokes, mouse clicks) by creating events – Different kinds of elements produce different events – We will concentrate on events from HTML form elements and commonly recognized events • You can put handlers on HTML form elements – If the event isn’t generated, the handler does nothing – A handler should be very short • Most handlers call a function to do their work 81

A simple event handler • <form> <input type="button" name="my. Button" value="Click. Me" onclick="alert('You clicked the button!'); "> </form> – The button is enclosed in a form – The tag is input type="button" – The name can be used by other Java. Script code – The value is what appears on the button – onclick is the name of the event being handled • The value of the onclick element is the Java. Script code to execute • alert pops up an alert box with the given text 82

Capitalization • Java. Script is case sensitive • HTML is not case sensitive • onclick="alert('You clicked the button!'); " – The underlined parts are HTML – The quoted string is Java. Script – You will frequently see onclick capitalized as on. Click • The Java naming convention is easier to read • This is fine in HTML, but an error if it occurs in Java. Script • Also note: Since we have a quoted string inside another quoted string, we need both single and double quotes 83

Common events • Most HTML elements produce the following events: – on. Click -- the form element is clicked – on. Dbl. Click -- the form element is clicked twice in close succession – on. Mouse. Down -- the mouse button is pressed while over the form element – on. Mouse. Over -- the mouse is moved over the form element – on. Mouse. Out -- the mouse is moved away from the form element – on. Mouse. Up -- the mouse button is released while over the form element – on. Mouse. Move -- the mouse is moved • In Java. Script, these should be spelled in all lowercase 84

Example: Simple rollover • The following code will make the text Hello red when the mouse moves over it, and blue when the mouse moves away <h 1 on. Mouse. Over="style. color='red'; " on. Mouse. Out="style. color='blue'; ">Hello </h 1> • Image rollovers are just as easy: <img src=". . /Images/duke. gif" width="55" height="68" on. Mouse. Over="src='. . /Images/duke_wave. gif' ; " on. Mouse. Out="src='. . /Images/duke. gif'; "> 85

Events and event handlers I • The following tables are taken from: Event Handler Load Applies to Occurs when Document body User loads the page in a browser Unload Document body User exits the page on. Unload Error Images, window Error on loading an image or a window on. Error Abort Images on. Abort User aborts the loading of an image on. Load 86

Events and event handlers II Event Applies to Occurs when Handler Key. Down Documents, images, User depresses on. Key. Down links, text areas a key Key. Up Documents, images, User releases a on. Key. Up links, text areas key Key. Press Documents, images, User presses on. Key. Press links, text areas or holds down a key Change Text fields, text areas, select lists User changes on. Change the value of an element 87

Events and event handlers III Event Applies to Occurs when Handler Mouse. Down Documents, buttons, links User on. Mouse. Down depresses a mouse button Mouse. Up Documents, buttons, links User releases a mouse button Click Buttons, radio User clicks a on. Click buttons, form element checkboxes, or link submit buttons, reset buttons, links on. Mouse. Up 88

Events and event handlers IV Event Applies to Occurs when Handler Mouse. Over Links User moves cursor over a link on. Mouse. Over Mouse. Out Areas, links Select Text fields, text areas User moves on. Mouse. Out cursor out of an image map or link User selects on. Select form element’s input field 89

Events and event handlers V Event Applies to Occurs when Handler Move Windows User or script moves a window on. Move Resize Windows User or script resizes a window on. Resize Drag. Drop Windows User drops an object onto the browser window on. Drag. Drop 90

Events and event handlers VI Event Applies to Occurs when Handler Focus Windows and all form elements User gives element input focus on. Focus Blur Windows and all form elements User moves focus to some other element on. Blur Reset Forms User clicks a Reset button on. Reset Submit Forms User clicks a on. Submit button 91

Back to the DOM • You can attach event handlers to HTML elements with very little knowledge of the DOM • However, to change what is displayed on the page requires knowledge of how to refer to the various elements • The basic DOM is a W 3 C standard and is consistent across various browsers – More complex features are browser-dependent • The highest level element (for the current page) is window, and everything else descends from that – Every Java. Script variable is a field of some object – In the DOM, all variables are assumed to start with “window. ” – All other elements can be reached by working down from there 92
- Slides: 92