Understanding Java Script The Three Layers of the





















































































- Slides: 85

Understanding Java. Script

The Three Layers of the Web

What is Java. Script? � Lightweight programming language � Adds interactivity to HTML pages � Works in all major browsers – IE, Mozilla, Firefox, Netscape, Opera and Safari � Is a complementary language – not used on own (embedded into HTML pages) � Primarily used for web-related programming � Consists of lines of executable code (statements)

What is Java. Script? � Is an interpreted language (no preliminary compilation) � No need to purchase a license � Used on the client-side (browser) of web application � Is the J in the acronym AJAX (Asynchronous Java. Script and XML) � Java. Script is not related to Java (Sun Microsystems)

What Java. Script Can Do � Gives web designers a programming tool (“code snippets”) � Dynamic effects on pages document. write(“<h 1>” + name + “</h 1>”) � Responds to user actions (event-driven) � Reads and writes HTML elements � Change page appearance – text, background � Pop-up windows – alert, confirm and prompt

Examples: Flashing grid of coloured squares (http: //bedford-computing. co. uk/Javascript. Examples/Fig 0101. html) How to change images on a web page How to affect web pages over time How to add randomness to web pages How to dynamically change what’s happening on a web page based on a user action Fish Weight Calculator (http: //bedfordcomputing. co. uk/Javascript. Examples/fish_weight_calculator. h tml)

What Java. Script Can Do � Image swaps and rollover effects � Drop-down menus � Performs calculations � Opens new browser windows � Form entry validation � Create cookies � Browser detection

History of Java. Script � Developed by Brendan Eich (Netscape) -1996 � Together with Sun Microsystems � Appeared in all major browsers since then � Microsoft developed its own version – JScript � Official name is ECMAScript (http: //www. ecma- international. org) � ECMA-262 is the official Java. Script standard

Java. Script Guidelines � Java. Script is case sensitive “myfunction” is not the same as “my. Function” “myvar” is not the same as “my. Var” � Java. Script ignores white space name=“Bedford”; name = “Bedford”; � Break up code lines (within strings) document. write(“Hello World!”);

Java. Script Guidelines � Java. Script once required a semicolon (; ) at the end of each statement � Group statements together into blocks by enclosing within curly braces { and } � Single line comments //This code will write “Hello World” to the page � Multi-line comments /*This code will write one header and two paragraphs to the page */

Object-Oriented Programming (OOP) Java. Script uses a model called OOP (object-orientated programming) � Objects (for example, a window) � Properties (for example, length) � Methods or actions (for example, open) � Events (for example, click) � Note: Many programmers argue the notion that Java. Script uses the object-orientated model.

Compiled vs. Intepreted Java. Script is an interpreted language � Code is run on the fly - no need to compile � Only need a text editor and browser � Does not perform as efficiently as compiled code � Easy to edit and embed in a web page � Compiled code tends to be platform specific – Java. Script is not

Java. Script Statement var small. Number = 4; Reserved Word Identifier Operator Literal

What Java. Script Can’t Do � Java. Script can’t be forced on a client Java. Script may be disabled in browser Java. Script is not supported in older browsers Java. Script’s fancy features may not be accessible to all – text-readers, text-only browsers, accessibility issues � Java. Script can’t cross domains � Java. Script can’t ensure data security � Java. Script can’t access server data or scripts

Beware!! � When you develop pages containing Java. Script you have little control over the final appearance or functionality of your page. � The script is parsed/interpreted by the browser and the page content displayed according to browser (User Agent) settings and other variables.

Remember……… � TEST YOUR PAGES IN AS MANY BROWSERS (AND OTHER PLATFORMS) AS POSSIBLE � Test in Mozilla Firefox (roots in Netscape), IE and Apple’s Safari � DON’T MAKE NAVIGATION OF YOUR WEBSITE DEPENDENT ON JAVASCRIPT!!! � ACCESSIBILITY IS A BIG ISSUE!!!

Text/Code Editors � Simplest is Note. Pad or MAC version � Better to use a slightly more complex editor � Free downloads from www. download. com � Look for Freeware or Shareware Small total file size

What to look for… � Provide colour coding � Assist in entering code � Code indentation � Validate syntax � Numbered lines � Code snippets � Debugging tools � Code and design views � Integrate with other languages – Java. Script, HTML, CSS, Java, ASP, PHP

Fundamentals of Java. Script � Using Java. Script with HTML pages � Where to put your code � Commenting your code � Special Characters and Escape Sequences � Reserved words

Parts of Java. Script � Variables and Constants � Types of Data � Naming Conventions � Operators � Statements and Expressions � Functions Global Functions User-Defined Functions � Objects – Properties, Methods, Event Handlers � Control Structures

Variables and Constants Information used in Java. Script falls into one of two categories: � Variables: Items that can contain different values at different times during script execution. Start with the keyword var followed by name. � Constants: Contain the same value throughout the execution of the script.

Types of Data Type Name Description Examples Boolean bool TRUE, FALSE Either TRUE or FALSE and is not case sensitive – but commonly uppercase Numeric/Floating float point numbers A fractional number with a decimal. 7. 34, -21. 89, 2. 31 e 3 May be negative and may use scientific notation Numeric/Integers Int A whole number without a decimal. 43, 928, -4 May be negative Numeric/Null null The absence of any value String string A series of characters (one of 256 “Mike”, “Seattle”, letters, numbers and special “ 1495 W. 18 th St. ” characters) enclosed in either single or double quotation marks Undefined A named variable that has not been assigned a value NULL

Naming Conventions � See later � Beware use of predefined or reserved words when naming variables and constants. Their use will cause errors in the code.

Operators � See later � Having created a variable or a constant, you are going to want to give it a value by assignment, calculation or comparison. � Java. Script has defined a number of operators of various types:

Operators Operator Explanation Arithmetic Performs arithmetic calculations on two operands which can be variables, numbers or a number and a variable Assignment Replace a value with another Bitwise Logical consequences turn specific bits in an integer on or off Comparison Compare two values and return TRUE or FALSE Logical consequences Other

Statements and Expressions � A statement is a line of code that is complete and correct in its syntax and performs a task. � Typically, a statement ends with a semi-colon � Often a single line of code ending with a semicolon � Can have many statement on a single line � Can have a statement spread over many lines � Statements contain one or more expressions � Expressions are anything that has a value! � Values are anything that can be assigned to a variable!

Functions � A function is a piece of script that does something and can be repeatedly called from a larger script � Global functions already exist � User-defined functions you need to write � Some functions require you to pass them values or arguments � Other functions simply return a value

Global Functions � These are predefined functions that are not object- specific � Java. Script does not have a large library of global functions � Java. Script has a large library of methods which are functions related to objects � Global functions include: escape(); eval(); is. Finite(); is. NAN(); parse. Float(); parse. Int(); unescape()

User-Defined Functions � Allows you to repeatedly use the same code � Allows economical use of code – don’t have to copy to different parts of the page � Easy editing � Simply create a function containing the code you want to repeat – and call that function from everywhere you want to use it � Putting function in the header means that it won’t be run until it is called � User-defined functions can also have one or more arguments that are passed to them , and may return a value after they are executed

Objects � Objects are the visual elements of a web page – windows, buttons, check boxes and dates � Can also be more abstract elements such as math calculations and arrays � There are many predefined objects � You can create your own custom objects as well

Predefined Objects � Identified by a keyword name – for example, window � You can have several instances of an object in a web page – each identified by a unique name � Each object can have properties (characteristics) � Each object can have methods (the things it can do) – for example, alert (), write() � Each object can have events (which effect it) – for example, mouse click � The relationship of an object to its constituents is shown by the use of the dot syntax

Properties � Objects have properties that allow you to describe them – distinguishing different occurrences of the same object from one another � For example you can modify a window by outer height and width, or inner display area � Some objects have only one property - for example, the string object has only one property – length. � Properties are applied to an object using the dot statement syntax: objectname. propertyname = “value”

Methods � Methods are actions that objects can perform � They can be considered predefined functions for objects � For example, to return the square root of three, use: math. sqrt(3); � Another example: window. alert(“Hello World”);

Event Handlers � Event handlers allow you to take advantage of events (or triggers) performed by the user – for example, mouse click or page load � The event handler recognises the event taking place and then performs one or more tasks – adding interactivity to the web page � Common event handlers are shown in the next slide:

Event Handlers Event Handler Event Trigger on. Abort An image’s loading is interrupted on. Blur Focus is removed from an element on. Change Contents of a form are changed on. Click An element is single-clicked on. Dbl. Click An element is double-clicked on. Drag. Drop An object is dragged-and-dropped into a window on. Error An error occurs when loading a web page or picture on. Focus The user places the focus on an element on. Key. Down The user presses a defined key on. Key. Press The user presses and holds down a defined key on. Key. Up The user releases a defined pressed key on. Load A web page completes loading in a browser

Event Handlers Event Handler Event Trigger on. Mouse. Down The user presses a mouse button on. Mouse. Move The user moves the mouse pointer on. Mouse. Out The user moves the mouse pointer from a link on. Mouse. Over The user moves the mouse pointer to a link on. Mouse. Up The user releases a mouse buton on. Move A window or frame is moved on. Open A web page opens in a browser on. Reset A form is reset on. Resize A window or frame is resized on. Select A field in a form is selected on. Submit A user submits a form on. Unload A user opens another web page

Control Structures � Simple scripts are executed from the first statement to the last statement without interruption � Often you will want the script to go one way or another – or re-execute a particular piece of code � This is the purpose of control structures: if/else while do-while for switch

The logical flow of an if statement

The logical flow of an if-else statement

The logical flow of a while loop

The logical flow of a do-while loop

The logical flow of a for loop

Where do you put your Java. Script? <html> <head> <title>A Web Page Title</title> <script type = "text/javascript"> // Java. Script goes here </script> </head> <body> <script type = "text/javascript"> // Java. Script can go here too </script> </body> </html>

Where do you put your Java. Script? <html> <head> <title>A Web Page Title</title> <script type = "text/javascript“ src = “myjavascript. js”> // Java. Script in external file </script> </head> <body> <script type = "text/javascript"> // Java. Script can go here too </script> </body> </html>

Java. Script in <body> tag is executed as it is encountered… <head> <title>A Web Page Title</title> <script type = "text/javascript"> // Java. Script Goes Here </script> </head> <body> <script type = "text/javascript"> document. write("hello"); document. write(" world"); </script> </body> </html>

Writing text to page <html> <body> <script type="text/javascript"> document. write("Hello World!"); </script> </body> </html>

Adding comments to handle older browsers <html> <body> <script type="text/javascript"> <!-document. write("Hello World!"); //--> </script> </body> </html>

Writing HTML tags on a page using Java. Script <html> <body> <script type="text/javascript"> document. write("<h 1>This is a header</h 1>"); </script> </body> </html>

First Web Project <html> <head> <title>My First Page</title> <script type = "text/javascript"> function yet. Another. Alert(text. To. Alert) { alert(text. To. Alert); } yet. Another. Alert("This is my first Java. Script!"); </script> </head> <body> </html>

First Web Project <html> <head> <title>My First Page</title> <script type = "text/javascript"> function yet. Another. Alert(text. To. Alert) { alert(text. To. Alert); } yet. Another. Alert("This is my first Java. Script!"); </script> </head> <body> <script type = "text/javascript"> yet. Another. Alert("This function has been called from the body of the page!"); </script> </body> </html>

First Web Project <html> <head> <title>My First Page</title> <script type = "text/javascript“ src = “myscript. js”> </script> </head> <body> <script type = "text/javascript"> yet. Another. Alert("This function has been called from the body of the page!"); </script> </body> </html>

First Web Project – What have we learned? � Java. Script code consists of lines (or statements) � Use the HTML <script> to embed code in HTML page <script type = "text/javascript“> � Every line (statement) ends with ; (semi-colon) � Code on HTML page is read/interpreted line by line from the top of the page

First Web Project – What have we learned? � Can be embedded using the <script> tag in either the <head> <body> � An external Java. Script file can also be linked to a web page (. js extension). <script type = "text/javascript“ src = “myscript. js”> � Don’t use the HTML <script> tag in the external. js file

First Web Project – What have we learned? � Statements can be grouped together as functions – which are created and named by the developer function yet. Another. Alert(text. To. Alert) { alert(text. To. Alert); } � Java. Script is case-sensitive � Keywords – for example, function – are in lowercase � Indentation is used to help readability!

First Web Project – What have we learned? � Use curly braces { } to group statements into blocks � Code in functions is only run when functions are ‘called’ � Functions can be called from the <head> or (more usually) the <body> yet. Another. Alert("This is my first Java. Script!"); yet. Another. Alert("This function has been called from the body of the page!");

First Web Project – What have we learned? � The function name is always followed by () � Arguments (or parameters) can be passed into a function: function yet. Another. Alert(text. To. Alert) { alert(text. To. Alert); } yet. Another. Alert("This is my first Java. Script!"); � Note the use of " " around literal strings.

First Web Project – What have we learned? There also pre-defined functions (or methods): alert(“My name is Sue”); or alert(text. To. Alert); or window. alert(“My name is Sue”) or window. alert(text. To. Alert);

Quick question!! � What is the purpose of using functions?

Variables � Variables are containers for storing values (literals) � Can be used and re-used � Rules for naming Begin with [a…z], [A…Z], or ‘_’ All subsequent characters [a…z], [A…Z], [1… 9] or ‘_’ Variables are case sensitive Should not use Java. Script keywords or reserved words

Good or Bad Variables? var bedfordvar 1 = “Bedford 1"; var Bedfordvar 2 = “Bedford 2"; var Bedford_var 3 = “Bedford 3"; var _Bedfordvar 4 = “Bedford 4"; var 1 Bedfordvar = “Bedford 5"; var Bedford var 2 = “Bedford 6"; var = “Bedford 7";

� Java. Script is ‘weakly typed’ � You do not have to declare a datatype � You do not even have to declare the variable before use � However, it is good practice to declare variable first � Arrays are indexes of similar items. Items must have the same datatype. Powerful when used with loops.

Datatypes: Null Integer (Decimal, Hexadecimal, Octal) Float (Decimal integer, decimal point, numbers to right of decimal point, and possibly, exponent) Boolean (datatype with two states only) String – collection of characters – surrounded by double or single quotes

Declaring a Variable var my. Variable; my. Variable = "some value"; or var my. Variable = "some value";

<head> <script language="Java. Script"> var my. Variable = "Hello"; </script> </head> <body> We created a variable in the header. <script language = “Java. Script”> document. write(“The variable contains: “ + my. Variable); </script> Outputting a variable </body>

<html> <head> Changing the value in </head> a variable <body> <script type="text/javascript"> var firstname; firstname="Fred"; document. write(firstname); document. write(" "); firstname="Tom"; document. write(firstname); </script> <p>The script above declares a variable, assigns a value to it, displays the value, changes the value, and displays the value again. </p> </body> </html>

What is a String? � Any sequence of characters – and can contain numbers, letters or other symbols Surrounded by double or single quotes � Valid: "Hello there" 'My Phone number is 123 -456 -7890‘ � Non-valid: "Hello' What is your name?

Concatenating Strings Combines two text strings into one longer text string: var my. Variable = "ab" + "cd"; or var this. Var = “cd”; var my. Variable = "ab" + this. Var;

<body> <script language="Java. Script"> <!— var my. Variable = "Hello"; var another. Variable = "there" var final. Results = my. Variable + " " + another. Variable; document. write(final. Results); // --> Concatenating </script> strings </body>

<body> Three ways of outputting <script language="Java. Script"> strings <!-var my. Greeting = “Hello”; document. write(my. Greeting); document. write(“ My Name is Sue”); window. alert(my. Greeting + “n. My Name is Sue”); // --> </script> </body>

String Character Codes � is the escape operator �” will literally place a quotation mark in a string �n is the new line character

Performing Calculations �Addition: For instance, 10 + 20 �Subtraction: For instance, 20 – 10 �Multiplication: For instance, 10 * 20 �Division: For instance, 20 / 10 Can use complex expressions: 100 / 5 – 10 100 / (5 – 10) var my. Variable = 100 / 5; var my. Variable = 100 / this. Var;

<body> <script language="Java. Script"> <!— var my. Variable = 100; var another. Variable = 200 var final. Results = my. Variable + another. Variable; document. write(final. Results); // --> </script> </body>

Operators �The assignment operator = is used to assign values to Java. Script variables. �The arithmetic operator + is used to add values together. y=5; z=2; x=y+z; �What value does x contain?

Arithmetic Operators Given that y=5, the table below explains the arithmetic operators: Operator Description Example + * Addition Subtraction Multiplication x=y+2 x=y-2 x=y*2 / % x=y/2 x=y%2 ++ Division Modulus (division remainder) Increment -- Decrement x=--y x=++y Result

Arithmetic Operators Given that y=5, the table below explains the arithmetic operators: Operator Description Example Result + * Addition Subtraction Multiplication x=y+2 x=y-2 x=y*2 x=7 x=3 x=10 / % Division Modulus (division remainder) Increment Decrement x=y/2 x=y%2 x=2. 5 x=1 x=++y x=--y x=6 x=4 ++ --

Assignment Operators Given that x=10 and y=5, the table below explains the assignment operators: Operator = += -= Example x=y x+=y x-=y Same As *= /= %= x*=y x/=y x%=y x=x*y x=x/y x=x%y x=x+y x=x-y Result

Assignment Operators Given that x=10 and y=5, the table below explains the assignment operators: Operator = += -= Example x=y x+=y x-=y Same As x=x+y x=x-y Result x=5 x=15 x=5 *= /= %= x*=y x/=y x%=y x=x*y x=x/y x=x%y x=50 x=2 x=0

What is the output? txt 1="What a very"; txt 2="nice day"; txt 3=txt 1+" "+txt 2;

Adding Strings and Numbers <body> <script type="text/javascript"> x=5+5; document. write(x); document. write(" "); x="5"+"5"; document. write(x); document. write(" "); x=5+"5"; document. write(x); document. write(" "); x="5"+5; document. write(x); document. write(" "); </script> <p>The common rule is: If you add a number and a string, the result will be a string. </p> </body>

Comparison and Logical Operators � Comparison and logical operators are used to test for true or false. � Comparison operators are used in logical statements to determine equality or difference between variables or values. � Logical operators are used in determine the logic between variables or values.

Comparison Operators Given that x=5, the table below explains the comparison operators: Operator Description == is equal to === is exactly equal to (value and type) Example x==8 is false x===5 is true x==="5" is false != > < >= <= x!=8 is true x>8 is false x<8 is true x>=8 is false x<=8 is true is not equal is greater than is less than is greater than or equal to is less than or equal to

How Comparison Operators can be used: Comparison operators can be used in conditional statements to compare values and take action depending on the result: if (age<18) document. write("Too young");

Logical Operators Given that x=6 and y=3, the table below explains the logical operators: Operator Description && and Example (x < 10 && y > 1) is true || or ! not (x==5 || y==5) is false !(x==y) is true

Conditional Operator Java. Script also contains a conditional operator that assigns a value to a variable based on some condition. The syntax is: variablename=(condition)? value 1: value 2 greeting=(visitor=="PM")? "Dear Prime Minister ": "Dear"; If the variable visitor has the value of "PM", then the variable greeting will be assigned the value "Dear Prime Minister " else it will be assigned "Dear".

Java. Script Security Issues � Issues: reading/writing client files, opening/closing user windows, reading information from other browser windows � The Sand Box – Java. Script’s Security Model � Signed Scripts � Same-Origin Security Policy � Cross-Site Scripting (XSS) � SQL Injection