Web Systems and Technologies Chapter 04. Java Script Content What is JavaScript The Foundation of JavaScript Syntax The Core language Objects in JavaScript Document Object Model (DOM) and The Browser Objects in JavaScript 2 The Foundation of JavaScript Syntax 3 What is JavaScript It is a scripting language that can be used to create client-side scripts and server-side scripts. JavaScript makes it easier to create dynamic and interactive Web pages. JavaScript is a scripting language developed by Sun Microsystems and Netscape.
JavaScript developed from Netscapes’s Livescript. Client applications run in a browser such as Netscape Navigator, Google Chrome, FireFox or Internet Explorer. 4 JavaScript Advantages JavaScript allows interactivity such as: Implementing form validation React to user actions, e. handle keys Changing an image on moving mouse over it Sections of a page appearing and disappearing Content loading and changing dynamically Performing complex calculations Custom HTML controls, e.
scrollable table Implementing AJAX functionality 5 What Can JavaScript Do? Can handle events Can read and write HTML elements and modify the DOM tree Can validate form data Can access / modify browser cookies Can detect the user’s browser and OS Can be used as object-oriented language Can handle exceptions Can perform asynchronous server calls (AJAX) 6 Embedding JavaScript in Web Page The JavaScript can be inserted into an HTML document in the following ways : Using SCRIPT tag: <script language="JavaScript"> <!-- JavaScript statements; //--> </script> Using an external File <script language="JavaScript“ src="filename.js"> </script> Using JavaScript Expressions within HTML Tag Attribute Values Using JavaScript in event handlers 7 JS Variables A variable is a container that refers to a memory location. It is used to hold values that may change while the script is executing. Variables follow some naming conventions. A variable is declared using the keyword ‘var’.
var A = 10; Variables have a scope that is determined by where they are declared in the script. Global Variable Local Variable Literals are fixed values that can be used in the script. 8 JS Variables (1) String type – string of characters var myName = "You can use both single or double quotes for strings"; Arrays var my_array = [1, 5.3, "aaa"]; Associative arrays (hash tables) var my_hash = {a:2, b:3, c:"text"}; 9 JS Data Types JavaScript has a relatively small set of data types. Numbers Logical or Boolean Strings Null JavaScript is case-sensitive.
In JavaScript, two variables of different types can be combined. example: A = “ This apple costs Rs.” + 5 will result in a string with the value "This apple costs Rs. 10 JS Data Type - Example <HTML> <HEAD> <SCRIPT LANGUAGE = "Javascript"> var A = "12" + 7.write(A); </SCRIPT> </HEAD> </HTML> 11 JS Literal - Types Integer – These can be expressed in decimal, hexadecimal and binary number system. Floating- point - These number can have a decimal point or an “e” or “”E” followed by an integer.
String - A string literal is zero or more characters enclosed in single or double quotation marks. Boolean - This can take only two values: True or False. null - The null type has only one value: null. Null implies no data.
12 Operators Operators take one or more variables or values (operands) and return a new value. JavaScript uses both binary and unary operators. Operators are classified depending on the relation they perform like: Arithmetic Operator: +, -, *, /, ++, -- Comparison Operator: ==, !=, >, >=, <, <= Logical Operator: &&, ||, ! String Operator Evaluation Operator Operator Precedence 13 Evaluation Operator These operators generally includes: Conditional operator (condition) ? trueVal : falseVal Assigns a specified value to a variable if a condition is true, otherwise assigns an alternate value if condition is false. status = (age >= 18) ? "adult" : "minor" Typeof operator The typeof operator returns a string indicating the type of the operand.write(typeof(x)); 14 Switch Statement The switch statement works like in C#: switch (variable) { switch-statements.html case 1: // do something break; case 'a': // do something else break; case 3.14: // another code break; default: // something completely different } 15 Loop Structures that control repetition in a program are known as loops.
The various types of loops include: For var counter; Do …. While for (counter=0; counter<4; counter++) { While alert(counter); } Break & continue while (counter < 5) { For….in alert(++counter); with } 16 Function JavaScript has several pre-defined functions that we can use within the script. Some of pre-defined JavaScript functions includes: eval function isNaN funtion Creating User Defined Functions function funcName(argument1,argument2,etc) { statements; } Calling a Function Return Statement 17 Function (1) Code structure – splitting code into parts Parameters Data comes in, processed, result returned come in here. function average(a, b, c) Declaring variables is { optional.
Type is never var total; declared. total = a+b+c; return total/3; } Value returned here. 18 Function Arguments and Return Value Functions are not required to return a value When calling function it is not obligatory to specify all of its arguments The function has access to all the arguments passed via arguments array function sum() { var sum = 0; for (var i = 0; i < arguments.length; i ++) sum += parseInt(arguments[i]); return sum; } alert(sum(1, 2, 4)); 19 Standard Popup Boxes Alert box with text and [OK] button Just a message shown in a dialog box: alert("Some text here"); Confirmation box Contains text, [OK] button and [Cancel] button: confirm("Are you sure?"); Prompt box Contains text, input field with default value: prompt ("enter amount", 10); 20 JavaScript Prompt – Example price = prompt("Enter the price", "10.00"); alert('Price + VAT = ' + price * 1.2); 21 The Core language Objects in JavaScript 22 Objects In JavaScript, almost "everything" is an object. Booleans can be objects (or primitive data treated as objects) Numbers can be objects (or primitive data treated as objects) Strings can be objects (or primitive data treated as objects) Dates are always objects Maths are always objects Regular expressions are always objects Arrays are always objects Functions are always objects Objects are objects In JavaScript, all values, except primitive values, are objects.
23 Properties and Methods To access the properties of the object, we must specify the object name and the property: objectName.propertyName To access the methods of an object, we must specify the object name and the required method: objectName.method() 24 Using objects When creating a Web page we can insert: Browser objects Built in script language objects (vary depending on the scripting language used) HTML elements We can also create our own objects for use in the programs. Object Hierarchy Browser Objects Script Objects HTML Elements 25 String object The string object is used to manipulate and work with strings of text. We can extract substrings and convert text to upper- or lowercase characters in a program. The general syntax is, stringName.propertyName or stringName.[,paramN]) where, objectName is the name of the new object instance.
objectType is a function that defined the type of the object. For example, Array. ] are the property values of the object 28 Create new Object With JavaScript, you can define and create your own objects. There are different ways to create new objects: Define and create a single object, using an object literal.
Define and create a single object, with the keyword new. Define an object constructor, and then create objects of the constructed type. Step 1: Create new object by create a function Step 2: Create new instant by using new operator 29 Creating String object There are 3 different methods of creating strings. Using the var statement and optionally assigning it to a value.
Using an assignment operator (=) with a variable name. Using the string () constructor. <script type = "text/javascript"> var str = “Steve Paris!" document.length) var pos=str.write(pos + "<br />") } else { document. function Customer( iD,name,address) { this.CustomeriD = iD; //property this.CustomerName = name; //property this.CustomerAddress = address; //property this.Displayinfor = information; //method } function DisplayInfor () { document.write(“ID: ” + this.CustomeriD + ”<br>”); document.write(“Name: ” + this.CustomerName + ”<br>” document.write(“Address: ” + this.CustomerAddress + ”<br>” } 31 Create new Object – Example (2) Step 2.
var cust = new Customer(); cust.CustomerName= “Steve Paris” cust.CustomerAddress= “12 Orange Street” In order to display customer’s information, we call Displayinfor() method: cust.Displayinfor() 32 Arrays Operations and Properties Declaring new empty array: var arr = new Array(); Declaring an array holding few elements: var arr = [1, 2, 3, 4, 5]; Appending an element / getting the last element: arr.push(3); var element = arr.length; Finding element's index in the array: arr.indexOf(1); 33 Math Object The Math object has properties and methods that represent advanced mathematical calculations. <script> function doCalc(x) { var a; a = Math.PI * x * x; alert ("The area of a circle with a radius of " + x + “ is " + a); } </script> 34 Math Object Example for (i=1; i<=20; i++) { var x = Math.write("Random number (" + i + ") in range " + "1.10 --> " + x + "<br/>"); } 35 Date Object The Date object provides date / calendar functions var now = new Date(); var result = "It is now " + now; document. <p id="timeField"></p> 36 Timers: setTimeout() Make something happen (once) after a fixed delay var timer = setTimeout('bang()', 5000); 5 seconds after this statement executes, this function is called clearTimeout(timer); Cancels the timer 37 Timers: setInterval() Make something happen repeatedly at fixed intervals var timer = setInterval('clock()', 1000); This function is called continuously per 1 second. clearInterval(timer); Stop the timer.
38 Date Object Example <html><head> <body BGCOLOR="#FFFFFF” onLoad="startclock()"> <title>Digital Clock - Status Bar</title> <script Language="JavaScript"> </body></html> var timeriD = null; var timerRunning = false; function stopclock (){ if(timerRunning) clearTimeout(timeriD); timerRunning = false; } function showtime () { var now = new Date(); var hours = now.getHours(); var minutes = now.getMinutes(); var seconds = now.status = timeValue; timeriD = setTimeout("showtime()",1000); timerRunning = true; 39 } Document Object Model (DOM) and The Browser Objects in JavaScript 40 Event Object - Concept Events are a result of an action done by the user An event may be user-generated or generated by the system Each event has an associated event object. The event object provides information on: the type of event the location of the cursor at the time of the event The event object is used as a part of an event handler 41 Event – Life Cycle Events are a result of an action done by the user An event may be user-generated or generated by the system Each event has an associated event object. The event object provides information on: the type of event the location of the cursor at the time of the event The event object is used as a part of an event handler 42 JavaScript Event Common events supported by JavaScript includes: onClick onChange onFocus onBlur onMouseOver onMouseOut onLoad onSubmit onMouseDown onMouseUp 43 onClick - Example The onClick event is generated whenever the user clicks the mouse button on certain form elements or on a hypertext link.