HTML

Published on January 2017 | Categories: Documents | Downloads: 64 | Comments: 0 | Views: 666
of 57
Download PDF   Embed   Report

Comments

Content

The Client Side in detail
JavaScript Daniel Anghel
University Politehnica of Bucharest [email protected]

October, 2010

Introduction Data Types and Values JavaScript Flow control

What is JavaScript Client-Side JavaScript Features JavaScript Syntax Rules

What is JavaScript?

JavaScript is a scripting language JavaScript is a lightweight, interpreted programming language with object-oriented capabilities. JavaScript was designed to add interactivity to HTML pages JavaScript is an untyped language. Variables do not need to have a type specified

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

What is JavaScript Client-Side JavaScript Features JavaScript Syntax Rules

Client-Side JavaScript Features

Control Document Appearance and Content Control the Browser Interact with HTML Forms Interact with the User Read and Write Client State with Cookies Other interesting features

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

What is JavaScript Client-Side JavaScript Features JavaScript Syntax Rules

Control Document Appearance and Content

Allows you to write arbitrary HTML into a document using write() method Document object allows generating document form the scratch. Since IE 5.5 and Netscape 6 W3DOM support was added. Defines standard to access every each HTML element and text by changing their CSS style attributes

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

What is JavaScript Client-Side JavaScript Features JavaScript Syntax Rules

Control the Browser
Several JavaScript objects allow control over the behavior of the browser. (e.g. Window, Location, History) Pop up dialog boxes to display messages and get simple user from user Open/close new browser windows with specified size, position etc History object allows you to move forward and back within the user’s browsing history Location object allows you to download and display the contents of any URL in any window or frame of the browser.

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

What is JavaScript Client-Side JavaScript Features JavaScript Syntax Rules

Interact with HTML Forms

Form object provide the ability to interact with HTML forms An objects contained into a Form object can read/write values from HTML forms Data from HTML form can be processed on the client side and results displayed back to user. Data from HTML form can be validated before sending it to server

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

What is JavaScript Client-Side JavaScript Features JavaScript Syntax Rules

Interact with User

JavaScript allows defining event handlers What are Event Handlers?

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

What is JavaScript Client-Side JavaScript Features JavaScript Syntax Rules

Interact with User

JavaScript allows defining event handlers What are Event Handlers? Arbitrary pieces of code to be executed when certain event occurs events are generated when certain action is done by the user(Submit button pressed, value entered in textbox etc.) Programming graphical user interface requires the existence of an event driven mechanism.

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

What is JavaScript Client-Side JavaScript Features JavaScript Syntax Rules

Read and Write Client State with Cookies
What is a Cookie?

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

What is JavaScript Client-Side JavaScript Features JavaScript Syntax Rules

Read and Write Client State with Cookies
What is a Cookie? A small amount of state data stored permanently or temporarily by the client. Cookies may be transmitted along with a web page by the server to the client The client store them locally When the client later requests the same or a related web page, it passes the relevant cookies back to the server JavaScript programs can read and write cookie values and can dynamically generate document content based on the value of cookies.
UPB Web Applications

Introduction Data Types and Values JavaScript Flow control

What is JavaScript Client-Side JavaScript Features JavaScript Syntax Rules

Other ”cookies” from JavaScript
JavaScript can change the image displayed by an <img> tag to produce image rollover and animation effects. JavaScript can interact with Java applets and other embedded objects that appear in the browser. The JavaScript Date object simplifies the process of computing and working with dates and times. The Navigator object has variables that specify the name and version of the browser that is running, as well as variables that identify the platform on which it is running. In client-side JavaScript 1.2, the Screen object provides information about the size and color-depth of the monitor on which the web browser is being displayed.
UPB Web Applications

Introduction Data Types and Values JavaScript Flow control

What is JavaScript Client-Side JavaScript Features JavaScript Syntax Rules

What JavaScript can not do

JavaScript does not have any graphics capabilities, except for the powerful ability to dynamically generate HTML (including images, tables, frames, forms, fonts, etc.) for the browser to display. For security reasons, client-side JavaScript does not allow the reading or writing of files. JavaScript does not support networking of any kind, except that it can cause the browser to download arbitrary URLs and it can send the contents of HTML forms across the network to server-side scripts and email addresses.

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

What is JavaScript Client-Side JavaScript Features JavaScript Syntax Rules

How to Put a JavaScript Into an HTML Page

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

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

What is JavaScript Client-Side JavaScript Features JavaScript Syntax Rules

How to Put a JavaScript Into an HTML Page - Discussion

To insert a JavaScript into an HTML page, use the <script> tag The word document.write is a standard JavaScript command for writing output to a page. Note: If we had not entered the <script> tag, the browser would have treated the document.write("Hello World!")command as pure text, and just write the entire line on the page.

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

What is JavaScript Client-Side JavaScript Features JavaScript Syntax Rules

Where to put JavaScript?

Head section - will be executed when called Body section - will be execute while the page loads External Script - to use the external script, point to the .js file in the ”src” attribute of the <script> tag:

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

What is JavaScript Client-Side JavaScript Features JavaScript Syntax Rules

Another sample
... <form name="convertorForm"> Value is: <input type="text" name="_valueField" size="12" onchange="calculate();"> Rate is: <input type="text" name="_rateField" size="12" onchange="calculate();"> Result is: <input type="text" name="_resultField" size="12"> </form> <script language="JavaScript"> function calculate() { var _theValue = document.convertorForm._valueField.value; var _theRate = document.convertorForm._rateField.value; _theResult = _theValue * _theRate; document.convertorForm._resultField.value = _theResult; } </script> ...
UPB Web Applications

Introduction Data Types and Values JavaScript Flow control

What is JavaScript Client-Side JavaScript Features JavaScript Syntax Rules

Lexical Rules
JavaScript is a case-sensitive language. Simple statements in JavaScript are generally followed by semicolons (;). However the semicolon is optional If semicolon is omitted then each statement needs to be paced on a separate line JavaScript, like Java, supports both C++ and C-style comments. Literals are data values that appears directly into program Identifiers are used to name variables and functions and to provide labels for certain loops in JavaScript code. These are a number of reserved words that cannot be used as identifiers
UPB Web Applications

Introduction Data Types and Values JavaScript Flow control

What is JavaScript Client-Side JavaScript Features JavaScript Syntax Rules

Reserved words in JavaScript

Table: Reserved words in JavaScript

break case catch continue default delete

do else false finally for function

if in instanceof new null return

switch this throw true try

typeof var void while with

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

What is JavaScript Client-Side JavaScript Features JavaScript Syntax Rules

Reserved words in JavaScript

Table: Other identifiers to avoid
arguments Array Boolean Date decodeURI decodeURIComponent encodeURI Error escape eval EvalError Function Infinity isFinite isNaN Math NaN Number Object parseFloat parseInt RangeError ReferenceError RegExp String SyntaxError TypeError undefined unescape URIError

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

What is JavaScript Client-Side JavaScript Features JavaScript Syntax Rules

Literals

12 1.2 "hello world" ’Hi’ true false /javascript/gi null

// // // // // // // //

The number twelve The number one point two A string of text Another string A boolean value The other boolean value A "regular expression" literal Absence of an object

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

What is JavaScript Client-Side JavaScript Features JavaScript Syntax Rules

JavaScript Variables

A variable is a ”container” for information you want to store. A JavaScript variable has no inherent limit to the amount of data it can hold. Rules for variable names:
Variable names are case sensitive They must begin with a letter or the underscore character

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

What is JavaScript Client-Side JavaScript Features JavaScript Syntax Rules

Variables

var x = "string"; var i = 12; alert(x); alert(i); //and because js is not a strong type later we can retype x = 5; alert(x);

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

What is JavaScript Client-Side JavaScript Features JavaScript Syntax Rules

JavaScript Functions

A function contains code that will be executed by an event or by a call to the function. A function can be called from anywhere within a page Defining a function
function functionname(var1,var2,...,varX) { some code }

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

Objects Java Script Objects Java Script Browser Objects

Everything is an object

There are five primitive data types:
Undefined Null Boolean Number String

Everything is an object, except for the primitive data types.

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

Objects Java Script Objects Java Script Browser Objects

Objects

Objects are composite data types Aggregate multiple values into a single unit and allows store and retrieve those values by name. The values contained may be:
primitive data types other objects functions

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

Objects Java Script Objects Java Script Browser Objects

Object Categories

There are three object categories in JavaScript: Native Objects - provided by JavaScript language. ex. Math, Date, Array Hosted Objects - provided to JavaScript by browsers. ex. document, window, form User defined Objects - created by developers A complete reference of JavaScript objects: http://www.w3schools.com/jsref/default.asp

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

Objects Java Script Objects Java Script Browser Objects

Creating Objects

Creating objects
function myClass(){ //Constructor function this.stringValue="Hello A02"; //property return 0; } var myObject = new myClass(); //notice the usage of "new" operator alert(typeof myObject); var myVar = myClass(); //without using the new operator alert(typeof myVar);

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

Objects Java Script Objects Java Script Browser Objects

Creating Objects

Creating objects
var circle = { x:0, y:0, radius:2 } var homer = { name: "Homer Simpson", age: 34, married: true, occupation: "plant operator", email: "[email protected]" }; var book = new Object( ); // Set a property in the object. book.title = "All about web apps"

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

Objects Java Script Objects Java Script Browser Objects

Object Methods
Object Methods
function Circle(radius){ function getArea(){ return (this.radius*this.radius*3.14); } function getCircumference(){ var diameter = this.radius*2; var circumference = diameter*3.14; return circumference; } this.radius = radius; this.getArea = getArea; this.getCircumference = getCircumference; }

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

Objects Java Script Objects Java Script Browser Objects

JavaScript Objects

Array Boolean Date Math Number String RegExp

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

Objects Java Script Objects Java Script Browser Objects

Are the String Useful in JavaScript?

A string is one of the fundamental building blocks of data that JavaScript works with. Any script that touches URLs or user entries in form text boxes works with strings. Most document object model properties are string values. Data that you read or write to a browser cookie is a string. The core JavaScript language has a repertoire of the common string manipulation properties and methods that you find in most programming languages.

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

Objects Java Script Objects Java Script Browser Objects

String Literals
A string is a sequence of zero or more Unicode characters enclosed within single or double quotes (’ or ”) String literals must be written on a single line they may not be broken across two lines. Character n should be included in this case
String Literal Samples "" // The empty string: it has zero characters ’testing’ "3.14" ’name="myform"’ "Wouldn’t you prefer O’Reilly’s book?" "This string\\nhas two lines" "pi is the ratio of a circle’s circumference to its diameter"

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

Objects Java Script Objects Java Script Browser Objects

HTML and JavaScript ”Strings”

In client-side JavaScript programming, JavaScript code often contains strings of HTML code, and HTML code often contains strings of JavaScript code. Note: When combining JavaScript and HTML, it is a good idea to use one style of quotes for JavaScript and the other style for HTML. <a href="" onclick="alert(’Thank you’)">Click Me</a>

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

Objects Java Script Objects Java Script Browser Objects

Escape Sequences in String Literals
The backslash character (\) has a special purpose in JavaScript strings.
Table: JavaScript escape sequences
Sequence \0 \b \t \n \v \f \r \” \’ \\ Character represented The NUL character (\u0000). Backspace (\u0008). Horizontal tab (\u0009). Newline (\u000A). Vertical tab (\u000B). Form feed (\u000C). Carriage return (\u000D). Double quote (\u0022). Apostrophe or single quote (\u0027). Backslash (\u005C).

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

Objects Java Script Objects Java Script Browser Objects

Concatenating (Joining) Strings

Within a single statement, use the plus (+) operator to concatenate multiple string values: To accumulate a string value across multiple statements, use the add-by-value (+=) operator:
String concatenation sample var result = ""; result = "My name is " + document.myForm.myName.value; result += " and my age is " + document.myForm.myAge.value;

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

Objects Java Script Objects Java Script Browser Objects

Regular Expressions
The purpose of a regular expression is to define a pattern of characters that can then used to compare against an existing string. To create a regular expression from a pattern the following syntax is use din JavaScript: Syntax for regular expressions
// Shortcut syntax var re = /pattern/ [g | i | gi]; // Formal constructor var re = new RegExp(["pattern", ["g "| "i" | "gi"]]);

g indicate that the pattern should be applied globally i indicate that the pattern is case insensitive
UPB Web Applications

Introduction Data Types and Values JavaScript Flow control

Objects Java Script Objects Java Script Browser Objects

String Methods Using Regular Expressions

match(regex) Returns substring in regex or null replace(regex, replacement) Substitutes regex with replacement string search(regex) Finds the starting position of regex in string split(regex) Removes regex from string for each occurrence

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

Objects Java Script Objects Java Script Browser Objects

Regular Expression Notation

Table: Regular Expression Notation
Character \b \B \d \D \s \S \w \W . Matches Word boundary Word nonboundary Numeral 0 through 9 Nonnumeral Single whitespace Single nonwhitespace Letter, numeral, or underscore Not a letter, numeral, or underscore Any character except a newline

Example /\bto/ matches ”tomorrow” /to\B/ matches ”stool” and ”tomorrow” /\d\d/ matches ”42” /\D\D/ matches ”to” /under\sdog/ matches ”under dog” /under\Sdog/ matches ”under-dog” /1\w/ matches ”1A” /1\W/ matches ”1%” /../ matches ”Z3”

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

Objects Java Script Objects Java Script Browser Objects

Regular Expression Notation

Table: Regular Expression Notation
Character [...] [ˆ ...] * ? + {n} {n,} {n,m} Matches Any one of the character set in brackets Negated character set Zero or more times Zero or one time One or more times Exactly n times n or more times At least n, at most m times Example /J[aeiou]y/ matches ”Joy” /J[ˆ eiou]y/ matches ”Jay” /\d*/ matches ””, ”5”, or ”444” /\d?/ matches ”” or ”5” /\d+/ matches ”5” or ”444” /\d{2}/ matches ”55” /\d{2,}/ matches ”555” /\d{2,4}/ matches ”5555”

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

Objects Java Script Objects Java Script Browser Objects

Accessing Substrings
Use the substring( ) method to copy a segment substring() sample
var myString = "Alesia is doing just fine."; var section = myString.substring(0, 10); // section is now "Alesia"

Use slice( ) method to set the end position at a point measured from the end of the string, using a negative value as the second parameter: slice() sample
var section = myString.slice(10, -6); // section is now "doing just"

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

Objects Java Script Objects Java Script Browser Objects

Changing String Case
To convert a string to all upper- or lowercase letters, exist two dedicated String object methods, toLowerCase( ) and toUpperCase( ) changing string case sample
var myString = "Targu Mures"; var lcString = myString.toLowerCase( ); var ucString = myString.toUpperCase( );

A common need for case conversion is preparing user entries for submission to a database that prefers or requires all uppercase (or all lowercase) letters. preparing for submission
<input type="text" name="firstName" id="firstName" size="20" onchange="this.value = this.value.toUpperCase( )" />
UPB Web Applications

Introduction Data Types and Values JavaScript Flow control

Objects Java Script Objects Java Script Browser Objects

Java Script Numbers

All integers and floating-point values are represented by the same data type in JavaScript: number. Internally, a JavaScript number is an IEEE double-precision 64-bit value. Both of the following statements produce a piece of data that evaluate to the same numbers: Creating Numbers
var myNum = 7; var myNum = new Number(7);

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

Objects Java Script Objects Java Script Browser Objects

Converting Between Numbers and Strings
To convert a number value to a string value use the toString( ) method of a number value: var numAsStringValue = numValue.toString( ); Or create an instance of a String object by passing the number as an argument to the String object: var numAsStringObject = new String(numValue); To convert a string to a number, use the parseInt( ) method if the desired result is an integer only, or the parseFloat( ) var intValue = parseInt(numAsString, 10); var floatValue = parseFloat(numAsString);
UPB Web Applications

Introduction Data Types and Values JavaScript Flow control

Objects Java Script Objects Java Script Browser Objects

JavaScript Date Object

Date object it is used to work with time and dates The Date object created using the new operator will initially contain the current time and date information Date info can be easily manipulate using the methods available for the Date object. The information about the current Date rely only on the internal clock of the client machine

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

Objects Java Script Objects Java Script Browser Objects

JavaScript Arrays
JavaScript Arrays are very flexible structures: JavaScript array is not limited to a specific size set at the time of its creation. Each entry in the array can hold data of any type. A reference to the array entry returns the entry’s value. To assign a value to an entry, use the simple assignment (=) operator. Array definition sample var mycars=new Array() mycars[0]="Saab" mycars[1]="Volvo" mycars[2]="BMW"
UPB Web Applications

Introduction Data Types and Values JavaScript Flow control

Objects Java Script Objects Java Script Browser Objects

Browser Objects

Window Properties and methods to manipulate an open window in a browser Navigator Contains information about the browser Screen Contains information about the visitor’s screen History Contains the URLs visited by the user (within a browser window) Object accessible from window.history Location contains information about the current URL. Object accessible from window.location

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

Objects Java Script Objects Java Script Browser Objects

HTML Forms - Form object

Many of the attributes of the ¡form¿ tag can be accessed as properties of the Form object. The forms[] array, allows accessing each Form object from a page in turn

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

If statement

If statement is the fundamental control statement that allows JavaScript to make decisions if statement syntax if (expression statement1 else statement2

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

Switch Statement
The switch statement handle situation when a variable needs to be checked of multiple values swith statement syntax switch(n) { case 1: execute code block 1 break case 2: execute code block 2 break default: code to be executed if n is different from case 1 and 2 } UPB Web Applications

Introduction Data Types and Values JavaScript Flow control

While Statement

while statement is the basic statement that allows JavaScript to perform repetitive actions. while statement syntax while (expression) statement

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

do/while Statement

The do/while loop is much like a while loop, except that the loop expression is tested at the bottom of the loop rather than at the top. do/while statement syntax do statement while (expression);

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

for Statement
The for statement provides a looping construct that is often more convenient than the while statement. for statement syntax for(initialize ; test ; increment) statement The for ... in statement can be used to iterate through the elements of an array or through the properties of an object for ... in statement syntax for (variable in object) statement

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

with Statement
This statement effectively adds object to the front of the scope chain, executes statement, and then restores the scope chain to its original state. with statement syntax
with (object) statement

with statement sample
with(document.forms[0]) { // Access form elements directly here. For example: name.value = ""; address.value = ""; email.value = ""; }

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

The HTML DOM
The HTML DOM is a W3C standard and it is an abbreviation for the Document Object Model for HTML. The HTML DOM defines a standard set of objects for HTML, and a standard way to access and manipulate HTML documents. All HTML elements, along with their containing text and attributes, can be accessed through the DOM. The contents can be modified or deleted, and new elements can be created. The HTML DOM is platform and language independent. It can be used by any programming language like Java, JavaScript, and VBScript.

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

The HTML DOM
With JavaScript you can restructure an entire HTML document. You can add, remove, change, or reorder items on a page. The DOM is separated into different parts (Core, XML, and HTML) and different levels:
Core DOM - defines a standard set of objects for any structured document HTML DOM - defines a standard set of objects for HTML documents XML DOM - defines a standard set of objects for XML documents

Complete reference and samples for DOM HTML http://www.w3schools.com/htmldom/default.asp
UPB Web Applications

Introduction Data Types and Values JavaScript Flow control

Accessing HTML elements

getElementById() Method of standard document object. Allows accessing an HTML element when it has an ID unique associated getElementByTagName() Returns an array containing all of the elements in the page, in the order that they appear in HTML

UPB

Web Applications

Introduction Data Types and Values JavaScript Flow control

Debugging JavaScript

Firebug - A Firefox browser extension that allows javascript debugging Dom Inspector - Firefox extension that allows analyzing the structure of the page.

UPB

Web Applications

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close